How to merge two dictionaries and keeping the potential different values in Python?

  • A+
Category:Languages

Let suppose that I have two dictionaries :

dic1 =  { "first":1, "second":4, "third":8}  dic2 =  { "first":9, "second":5, "fourth":3} 

Is it a straightforward way to obtain something like (multiples values are in the following written within lists, but tuples or whatever are fine too, I guess, for the use I will need)

dic3 =  { "first":[1,9], "second":[4,5], "third":[8], "fourth":[3]} 

 


Here's a naive solution; copy one of the dictionaries over to the result and iterate over the other dictionary's keys and values, adding arrays to the result as necessary. Since there are only two dictionaries, no merge array will have more than 2 items; no need to check type.

dic1 = {"first": 1, "second": 4, "third": 8}  dic2 = {"first": 9, "second": 5, "fourth": 3} dic3 = dict(dic2)  for k, v in dic1.items():     dic3[k] = [dic3[k], v] if k in dic3 else v  print(dic3) 

Output:

{'first': [9, 1], 'second': [5, 4], 'fourth': 3, 'third': 8} 

Try it out.

Use else [v] in place of else v if you'd like single-element items in their own list.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: