在字典中实现结果的最佳pythonic方式

时间:2017-10-09 13:49:08

标签: python

有没有更简单的方法在dict3中获得结果?

我需要在dict3中得到这个:

{'Runes': ['Ber', 'Ko'], 
 'Swords': ['Long swords', 'Short sword'], 
 'Gold': ['12','125'], 
 'Coal':[], 
 'Wood': [], 
 'Water':['21']}

这是我的最佳解决方案:

dict1 = {'Runes':['Ber','Ko'],'Swords':['Long sword'],'Gold':['','12','',''], 'Coal':['','']}
dict2 = {'Swords':['Short sword'],'Gold':['125'],'Wood':['',''],'Water':['','', '21'], 'Coal':['']}
dict3 = {}

for k1 in dict1.keys():
    if k1 not in dict3.keys():
       dict3.setdefault(k1, '')

for k2 in dict2.keys():
    if k2 not in dict3.keys():
       dict3.setdefault(k2, '')

for k3,v3 in dict3.items():
    for k1,v1 in dict1.items():
        if k3 == k1:
            dict3[k3] = v1

for k3,v3 in dict3.items():
    for k2,v2 in dict2.items():
        if k3 == k2 and type(v3) == str:
            dict3[k3] = v2

for k3,v3 in dict3.items():
    for k2,v2 in dict2.items():
        if k3 == k2 and v2 not in v3 and v2 != v3:
            dict3[k3] = v3 + v2

for k3,v3 in dict3.items():
    for k2,v2 in dict2.items():
        if k3 == k2 and '' in v3:
            s = []
            for i in v3:
                if i not in ['']:
                    s.append(i)
            dict3[k3] = s

1 个答案:

答案 0 :(得分:2)

我会使用defaultdict(这样您就不必检查字典中是否已存在给定的键),并filter删除空值:

from collections import defaultdict

dict3 = defaultdict(list)
all_dicts = [dict1, dict2]

for data in all_dicts:
    for key, values in data.items():
        values = filter(len, values)
        dict3[key].extend(values)