简体   繁体   English

如何在不覆盖数据的情况下合并两个具有相同键的字典?

[英]How to merge two dictionaries with the same keys without overwriting data?

I've got an assignment where I need to take two csv's and turn the information within them into two dictionaries.我有一个任务,我需要拿两个 csv 并将其中的信息转换成两个字典。 The keys for both dictionaries are the same, I just need the information from one dictionary to be added into the keys instead of overwriting.两个字典的键是相同的,我只需要将一本字典中的信息添加到键中而不是覆盖。 Example:例子:

dictionary 1 - 'key1' : ['place1' , 'web address', 'phone number']

dictionary 2 - 'key1' : ['place2', 'different web address', 'different phone number']

I'd like the final dictionary to look something like this:我希望最终的字典看起来像这样:

finalDictionary - 'key1' : [['place1' , 'web address', 'phone number'], ['place2', 'different web address', 'different phone number']]  

I'd use a defaultdict and iterate through all the keys/values in the dicts to append all the values to the lists in the final dict:我会使用defaultdict并遍历 dict 中的所有键/值,以将所有值附加到最终 dict 中的列表中:

>>> dict1 = {'key1' : ['place1' , 'web address', 'phone number']}
>>> dict2 = {'key1' : ['place2', 'different web address', 'different phone number']}
>>> from collections import defaultdict
>>> final_dict = defaultdict(list)
>>> for d in (dict1, dict2):
...     for k, v in d.items():
...         final_dict[k].append(v)
... 
>>> dict(final_dict)
{'key1': [['place1', 'web address', 'phone number'], ['place2', 'different web address', 'different phone number']]}

Just make a list of the values from both dictionaries.只需列出两个字典中的值即可。 You can use a dictionary comprehension to do this for all keys in the dictionaries.您可以使用字典理解为字典中的所有键执行此操作。

finalDictionary = {key: [dictionary1[key], dictionary2[key]] for key in dictionary1}
dct_1 = {'key1' : ['place1' , 'web address', 'phone number']}
dct_2 = {'key1' : ['place2', 'different web address', 'different phone number']}

final_dct = {'key1':[dct['key1'] for dct in [dct_1, dct_2]]}

(or better) (或更好)

list_of_dct = [{'key1': [stuff]},
               {'key1': [more stuff]},
              ]
final_dct = {'key1':[dct['key1'] for dct in list_of_dct]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM