我有大约1000个这样的字典。
x = {'a':1, 'b': 2, 'c':5}
y = {'b':10, 'c': 11}
z = {'e':5, 'b': 2}
我想要一个像这样的合并字典。
f = {'a':[1,0,0], 'b': [2,10,2], 'c':[5,11,0], 'e':[0,0,5]}
有没有迭代的方法来做到这一点。在创建最终字典后,我想创建一个矩阵,其中a,b,c,e将是具有三行的列标题,如下所示:
a b c e
1 2 5 0
0 10 11 0
0 2 0 5
答案 0 :(得分:1)
keys = ('a', 'b', 'c', 'e')
dicts = (x, y, z)
f = {k: [d.get(k, 0) for d in dicts] for k in keys}
或者作为一个单行:
f = {k: [d.get(k, 0) for d in (x, y, z)] for k in ('a', 'b', 'c', 'e')}
答案 1 :(得分:0)
您可以使用dict.viewkeys
和reduce
功能获取密钥,然后使用collections.defaultdict
将相应的值附加到密钥:
>>> x = {'a':1, 'b': 2, 'c':5}
>>> y = {'b':10, 'c': 11}
>>> z = {'e':5, 'b': 2}
>>> l=[x,y,z]
>>> keys=reduce(lambda i,j: i | j ,[j.viewkeys() for j in l])
>>> from collections import defaultdict
>>> d=defaultdict(list)
>>> for k in keys :
... for i in l:
... d[k].append(i.get(k,0))
...
>>> d
defaultdict(<type 'list'>, {'a': [1, 0, 0], 'c': [5, 11, 0], 'b': [2, 10, 2], 'e': [0, 0, 5]})
然后你可以创建合适的矩阵:
>>> [[i]+j for i,j in d.items()]
[['a', 1, 0, 0], ['c', 5, 11, 0], ['b', 2, 10, 2], ['e', 0, 0, 5]]
答案 2 :(得分:0)
以下是执行这两项任务的方法:
from collections import defaultdict
dicts = [{'a':1, 'b': 2, 'c':5},
{'b':10, 'c': 11},
{'e':5, 'b': 2}]
# determine what keys exist in the dictionaries and sort them
keys = sorted(reduce(lambda a,b: a|b, (set(d) for d in dicts)))
f = defaultdict(list)
for k in keys:
for d in dicts:
f[k].append(d.get(k, 0))
print 'merged\n f: {}'.format(dict(f))
matrix = [keys] + [[d.get(k, 0) for k in keys] for d in dicts]
print '\nmatrix:'
for row in matrix:
print ' '.join('{:>2}'.format(elem) for elem in row)
输出:
merged
f: {'a': [1, 0, 0], 'c': [5, 11, 0], 'b': [2, 10, 2], 'e': [0, 0, 5]}
matrix:
a b c e
1 2 5 0
0 10 11 0
0 2 0 5