将dic中的键及其值分割为多个键/值

时间:2015-07-21 17:32:50

标签: python python-2.7

我有以下词:

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'。

3 个答案:

答案 0 :(得分: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']}

答案 1 :(得分: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

答案 2 :(得分:0)

你想做的就是这个:

  1. 提取您要分割的密钥
  2. 拆分并将其分配到新列表
  3. 将密钥的值分配给新列表的列表并将其附加到新密钥
  4. 删除旧密钥和值
  5. 让你入门

    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]