-2

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?

2 Answers2

1

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}
S.B
  • 13,077
  • 10
  • 22
  • 49
-1
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}
ibigbug
  • 104
  • 1
  • 7
  • 1
    Note that ``dict.keys`` are already set-like; there is no need to convert them to sets explicitly. For example, ``dict1.update(dict.fromkeys(dict2.keys() - dict1.keys(), 0))`` works out of the box. – MisterMiyagi Sep 13 '21 at 10:25
  • The order of the key-value pairs in you answer doesn't match to the OP's requested output. – S.B Sep 13 '21 at 10:52
  • why would anyone care about the order of a dict without using an [OrderedDict](https://docs.python.org/3/library/collections.html#collections.OrderedDict) ? – ibigbug Sep 13 '21 at 12:22
  • @MisterMiyagi that's right, the dict keys are already hashed sets – ibigbug Sep 13 '21 at 12:23
  • 1
    @ibigbug since python 3.6, dictionaries are ordered (insertion order) – S.B Sep 13 '21 at 12:34
  • @SorousHBakhtiary thank you good to know: https://mail.python.org/pipermail/python-dev/2017-December/151283.html This makes me started questioning `Explicit is better than implicit. # who expects a "hashmap" that has ordered keys` and `Simple is better than complex. # purpose of OrderedDict is to let people know that a dict is just a dict, not an "OrderedDict" ` but anyways :) – ibigbug Sep 13 '21 at 14:23