我有一个包含多个dict
的tupple
,其中每个dict
都包含一个列表:
({'num' : [1, 2, 3], 'let': ['a', 'b', 'c']},
{'num' : [4, 5, 6], 'let': ['d', 'e', 'f']},
{'num' : [7, 8, 9], 'let': ['g', 'h', 'i']})
我想将所有dict
连接成一个dict
,其中包含一长串前dict
的值:
{'let': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'],
'num': [1, 2, 3, 4, 5, 6, 7, 8, 9]}
到目前为止,我尝试的所有内容要么给了我错误,要么导致输出的list
为list
s,而不是单个列表。
字典、键和.extend
的简单循环??
td = ({'num' : [1, 2, 3], 'let': ['a', 'b', 'c']},
{'num' : [4, 5, 6], 'let': ['d', 'e', 'f']},
{'num' : [7, 8, 9], 'let': ['g', 'h', 'i']})
d = td[0]
for e in td[1:]:
for k, v in e.items():
d[k].extend(v)
d
Out[42]:
{'let': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'],
'num': [1, 2, 3, 4, 5, 6, 7, 8, 9]}
您可以使用collections.defaultdict
:
from collections import defaultdict
d= defaultdict(list)
s = ({'num' : [1, 2, 3], 'let': ['a', 'b', 'c']},
{'num' : [4, 5, 6], 'let': ['d', 'e', 'f']},
{'num' : [7, 8, 9], 'let': ['g', 'h', 'i']})
for i in s:
d['num'].extend(i['num'])
d['let'].extend(i['let'])
print(dict(d))
输出:
{'num': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'let': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']}
或者,没有defaultdict
:
s = ({'num' : [1, 2, 3], 'let': ['a', 'b', 'c']},
{'num' : [4, 5, 6], 'let': ['d', 'e', 'f']},
{'num' : [7, 8, 9], 'let': ['g', 'h', 'i']})
new_s = {"num" if all(isinstance(d, int) for d in a) else "let":a for a in [reduce(lambda x, y:x+y, c) for c in zip(*[[b[-1] for b in i.items()] for i in s])]}
输出:
{'num': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'let': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']}
假设你的键总是相同的,你可以迭代第一个字典的键,并通过将列表链接在一起来构建合并的字典:
import itertools
d = ({'num' : [1, 2, 3], 'let': ['a', 'b', 'c']},
{'num' : [4, 5, 6], 'let': ['d', 'e', 'f']},
{'num' : [7, 8, 9], 'let': ['g', 'h', 'i']})
r = {k:list(itertools.chain.from_iterable(sd[k] for sd in d)) for k in d[0]}
结果:
{'num': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'let': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']}