Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two dictionaries with same key names [duplicate]

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]) 
like image 644
nasia jaffri Avatar asked Nov 08 '13 15:11

nasia jaffri


People also ask

Can you merge two dictionaries?

You can merge two dictionaries by iterating over the key-value pairs of the second dictionary with the first one.

Can dictionary have duplicate key values?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

Can you duplicate keys in dictionaries?

Why you can not have duplicate keys in a dictionary? You can not have duplicate keys in Python, but you can have multiple values associated with a key in Python. If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary.


Video Answer


1 Answers

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:

#! /usr/bin/env python3 import copy import itertools   def main():     dict_a = dict(a=[1], b=[2])     dict_b = dict(b=[3], c=[4])     complete_merge = merge_dicts(dict_a, dict_b, True)     print(complete_merge)     resolved_merge = merge_dicts(dict_a, dict_b, False)     print(resolved_merge)   def merge_dicts(a, b, complete):     new_dict = copy.deepcopy(a)     if complete:         for key, value in b.items():             new_dict.setdefault(key, []).extend(value)     else:         for key, value in b.items():             if key in new_dict:                 # rename first key                 counter = itertools.count(1)                 while True:                     new_key = f'{key}_{next(counter)}'                     if new_key not in new_dict:                         new_dict[new_key] = new_dict.pop(key)                         break                 # create second key                 while True:                     new_key = f'{key}_{next(counter)}'                     if new_key not in new_dict:                         new_dict[new_key] = value                         break             else:                 new_dict[key] = value     return new_dict   if __name__ == '__main__':     main() 

The program displays the following representation for the two merged dictionaries:

{'a': [1], 'b': [2, 3], 'c': [4]} {'a': [1], 'b_1': [2], 'b_2': [3], 'c': [4]} 
like image 176
Noctis Skytower Avatar answered Sep 28 '22 10:09

Noctis Skytower