Home > front end >  How to merge two dictionaries with the same keys without overwriting data?
How to merge two dictionaries with the same keys without overwriting data?

Time:11-11

I've got an assignment where I need to take two csv's and turn the information within them into two dictionaries. 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']]  

CodePudding user response:

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:

>>> 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']]}

CodePudding user response:

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}

CodePudding user response:

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]}
  • Related