Search code examples
python-3.xdictionaryfor-loopcombinationsdictionary-comprehension

How to merge two dictionaries and setting new key values to 0?


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?


Solution

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