Home > Software design >  How to merge two dictionaries and setting new key values to 0?
How to merge two dictionaries and setting new key values to 0?

Time:09-17

I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. I need to have to following input and output

Let's say we compare two sentences "I like potatoes" and "I like tomatoes"

input

dict1= {"I": 1, "like":1,"potatoes":1}
dict2= {"I": 1, "like":1,"tomatoes":1}

To compare them we need them in the following output

dict1 ={"I": 1, "like":1,"potatoes":1,"tomatoes":0}
dict2 ={"I": 1, "like":1,"potatoes":0,"tomatoes":1}

What is the best way to do this?

CodePudding user response:

Try this (python 3.9 for | dictionary merge operator) :

dict1 = {"I": 1, "like": 1, "potatoes": 1}
dict2 = {"I": 1, "like": 1, "tomatoes": 1}

union = dict1 | dict2

res1 = {k: dict1.get(k, 0) for k in union}
res2 = {k: dict2.get(k, 0) for k in union}

print(res1)
print(res2)

output :

{'I': 1, 'like': 1, 'potatoes': 1, 'tomatoes': 0}
{'I': 1, 'like': 1, 'potatoes': 0, 'tomatoes': 1}

CodePudding user response:

In [14]: dict1= {"I": 1, "like":1,"potatoes":1}
    ...: dict2= {"I": 1, "like":1,"tomatoes":1}

In [15]: keys1 = dict1.keys()  # dict keys are set-like: https://docs.python.org/3/library/stdtypes.html#dict-views

In [16]: keys2 = dict2.keys()  # get keys of dict2 in another set()

In [17]: dict1.update(dict.fromkeys(keys2 - keys1, 0))  # to build result from the items in dict1 and the "keys in dict2 but not in dict1" with value 0

In [18]: dict1
Out[18]: {'I': 1, 'like': 1, 'potatoes': 1, 'tomatoes': 0}

In [19]: dict2.update(dict.fromkeys(keys1 - keys2, 0))  # same here

In [20]: dict2
Out[20]: {'I': 1, 'like': 1, 'tomatoes': 1, 'potatoes': 0}
  • Related