[英]How can I combine dictionaries with the same keys?
I have a list of dictionaries like so:我有一个这样的字典列表:
dicts = [
{'key_a': valuex1,
'key_b': valuex2,
'key_c': valuex3},
{'key_a': valuey1,
'key_b': valuey2,
'key_c': valuey3},
{'key_a': valuez1,
'key_b': valuez2,
'key_c': valuez3}
]
I would like to take these and construct a big dictionary like so:我想用这些来构建一个像这样的大字典:
big_dict = {
'key_a': [valuex1, valuey1, valuez1],
'key_b': [valuex2, valuey2, valuez2],
'key_c': [valuex3, valuey3, valuez3]
}
Is there any elegant " zip "-like way for me to do this?有什么优雅的“ zip ”之类的方法可以让我做到这一点吗?
All the keys are always going to be identical.所有的键总是相同的。
big_dict = {}
for k in dicts[0]:
big_dict[k] = [d[k] for d in dicts]
Or, with a dict comprehension :或者,通过听写理解:
{k: [d[k] for d in dicts] for k in dicts[0]}
You can use collections.defaultdict
.您可以使用collections.defaultdict
。 The benefit of this solution is it does not require keys to be consistent across dictionaries, and it still maintains the minimum O( n ) time complexity.这个解决方案的好处是它不需要键在字典之间保持一致,并且它仍然保持最小的 O( n ) 时间复杂度。
from collections import defaultdict
dict_list = [{'key_a': 'valuex1', 'key_b': 'valuex2', 'key_c': 'valuex3'},
{'key_a': 'valuey1', 'key_b': 'valuey2', 'key_c': 'valuey3'},
{'key_a': 'valuez1', 'key_b': 'valuez2', 'key_c': 'valuez3'}]
d = defaultdict(list)
for myd in dict_list:
for k, v in myd.items():
d[k].append(v)
Result:结果:
print(d)
defaultdict(list,
{'key_a': ['valuex1', 'valuey1', 'valuez1'],
'key_b': ['valuex2', 'valuey2', 'valuez2'],
'key_c': ['valuex3', 'valuey3', 'valuez3']})
If all the dicts have the same set of keys, this will work:如果所有的字典都有相同的键集,这将起作用:
dict((k, [d[k] for d in dictList]) for k in dictList[0])
If they may have different keys, you'll need to first built a set of keys by doing set unions on the keys of the various dicts:如果它们可能有不同的键,您需要首先通过对各种字典的键执行集合联合来构建一组键:
allKeys = reduce(operator.or_, (set(d.keys()) for d in dictList), set())
Then you'll need to protect against missing keys in some dicts:然后你需要防止在某些指令中丢失键:
dict((k, [d[k] for d in [a, b] if k in d]) for k in allKeys)
If you are happy to use a 3rd party library you can use Pandas.如果您乐于使用 3rd 方库,则可以使用 Pandas。 The pd.DataFrame
constructor accepts a list of dictionaries directly: pd.DataFrame
构造函数直接接受字典列表:
import pandas as pd
res = pd.DataFrame(dictList).to_dict(orient='list')
{'key_a': ['valuex1', 'valuey1', 'valuez1'],
'key_b': ['valuex2', 'valuey2', 'valuez2'],
'key_c': ['valuex3', 'valuey3', 'valuez3']}
You can merge dictionaries in the following way:您可以通过以下方式合并字典:
def merge_dicts(dict_list, separator=''):
"""
Merges list of dictionaries to a single dictionary, Concatenates values with the same key.
:param dict_list: list of dictionaries to be merged.
:param separator: separator to be inserted between values of same key.
:return: Merged dictionary.
"""
return {k1: separator.join([d[k1] for d in dict_list if k1 in d])
for k1 in set(reduce(lambda x, y: x+y, [k.keys() for k in dict_list]))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.