2015-07-21 95 views
0

我有以下DIC:分裂在DIC和其值多键的键/值

dic = {'shape': ['a', 'b', 'c'], 'item1_item2_item3': ['1_2_3', '5_6_10', '3_7_9']} 

我想将其转换为:

dic = {'shape': ['a', 'b', 'c'], 'item1': ['1', '2', '3'], 'item2': ['5', '6', '10'], 'item3': ['3', '7', '9']} 

基本上,我想拆基于'_'并且使新的键/值超出原始键及其值。

第二个键的大小可能有更多的项目;例如'item1_item2,item3,item4'。

+2

你自己已经尝试过什么了吗? –

+0

我将文件保存到csv并通过逐行读取再次打开它。 – Omar

回答

1

使用zip()将分割键和值配对;你想建立一个新的字典在这里:

new = {} 
for key, value in dic.items(): 
    if '_' not in key: 
     new[key] = value 
     continue 

    for new_key, new_value in zip(key.split('_'), value): 
     new[new_key] = new_value.split('_') 

你可以在一个字典解析醪这一点,但它变得相当困难遵循:

{nk: (nv.split('_') if '_' in k else v) 
for k, v in dic.items() for nk, nv in zip(k.split('_'), v)} 

演示:

>>> dic = {'shape': ['a', 'b', 'c'], 'item1_item2_item3': ['1_2_3', '5_6_10', '3_7_9']} 
>>> new = {} 
>>> for key, value in dic.items(): 
...  if '_' not in key: 
...   new[key] = value 
...   continue 
...  for new_key, new_value in zip(key.split('_'), value): 
...   new[new_key] = new_value.split('_') 
... 
>>> new 
{'item2': ['5', '6', '10'], 'item3': ['3', '7', '9'], 'shape': ['a', 'b', 'c'], 'item1': ['1', '2', '3']} 
>>> {nk: (nv.split('_') if '_' in k else v) 
... for k, v in dic.items() for nk, nv in zip(k.split('_'), v)} 
{'item2': ['5', '6', '10'], 'item3': ['3', '7', '9'], 'shape': ['a', 'b', 'c'], 'item1': ['1', '2', '3']} 
0

您可以使用my_string.split("_")拆分字符串以获取列表字符串。这里有一个解决方案,拆分字符串和键并指定新值:

dic = {'shape': ['a', 'b', 'c'], 'item1_item2_item3': ['1_2_3', '5_6_10', '3_7_9']} 

new_dic = {} 

for k in dic.keys(): 
    val = dic[k] 
    subkeys = k.split("_") 

    if len(subkeys) > 1: 
     for s in range(len(subkeys)): 
      subkey = subkeys[s] 
      subvals = val[s].split("_") 
      new_dic[subkey] = subvals 

    # this handles the case where the key has no underscores 
    else: 
     new_dic[k] = val 

print new_dic 
0

你想做的事是这样的:

  1. 提取物,你想分裂的关键
  2. 把它分解并分配它以一个新的列表
  3. assing键的值到新的目录列表,并将它附加到新的关键
  4. 删除旧的密钥和值

为了让你开始

dic = {item: "whatever", item1_item2_item3: [1,2,3], [2,3,4]. [4,5,6]} 
copy = dic[item1_item2_item3] 
name = item1_item2_item3 
name = name.split("_") 
#this make a list like this: [item1, item2, item3] 
for i in len(name): 
    dic[name[i]] = copy[i] 

del.dic[item1_item2_item3]