How to merge 2 dictionaries with the same key names
source link: https://www.codesd.com/item/how-to-merge-2-dictionaries-with-the-same-key-names.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to merge 2 dictionaries with the same key names
This question already has an answer here:
- append vs. extend 19 answers
I am new to Python and am trying to write a function that will merge two dictionary objects in python. For instance
dict1 = {‘a’:[1], ‘b’:[2]}
dict2 = {‘b’:[3], ‘c’:[4]}
I need to produce a new merged dictionary
dict3 = {‘a’:[1], ‘b’:[2,3], ‘c’:[4]}
Function should also take a parameter “conflict” (set to True or False). When conflict is set to False, above is fine. When conflict is set to True, code will merge the dictionary like this instead:
dict3 = {‘a’:[1], ‘b_1’:[2],’b_2’:[3], ‘c’:[4]}
I am trying to append the 2 dictionaries, but not sure how to do it the right way.
for key in dict1.keys():
if dict2.has_key(key):
dict2[key].append(dict1[key])
If you want a merged copy that does not alter the original dicts and watches for name conflicts, you might want to try this solution:
>>> dict1 = {'a': [1], 'b': [2]}
>>> dict2 = {'b': [3], 'c': [4]}
>>> import copy
>>> import itertools
>>> def merge(a, b, conflict):
new = copy.deepcopy(a)
if conflict:
for key, value in b.items():
if key in new:
counter = itertools.count(1)
# Rename 1st key.
while True:
name = '{}_{}'.format(key, next(counter))
if name not in new:
new[name] = new[key]
del new[key]
break
# Create 2nd key.
while True:
name = '{}_{}'.format(key, next(counter))
if name not in new:
new[name] = value
break
else:
new[key] = value
else:
for key, value in b.items():
new.setdefault(key, []).extend(value)
return new
>>> merge(dict1, dict2, False)
{'c': [4], 'b': [2, 3], 'a': [1]}
>>> merge(dict1, dict2, True)
{'b_2': [3], 'b_1': [2], 'c': [4], 'a': [1]}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK