Python tip 9: applying set-like operations for dictionaries
You can merge two dictionaries using the |
operator (similar to union of sets). If a key is found in both the dictionaries, the insertion order of the first dictionary will be maintained, but the value of the second dictionary will be used. In other words, keys are updated to the new value during the merge.
>>> marks_1 = {'Rahul': 86, 'Ravi': 92, 'Rohit': 75}
>>> marks_2 = {'Jo': 89, 'Rohit': 78, 'Joe': 75, 'Ravi': 100}
# use unpacking, i.e. {**d1, **d2} for Python 3.8 and below versions
>>> marks_1 | marks_2
{'Rahul': 86, 'Ravi': 100, 'Rohit': 78, 'Jo': 89, 'Joe': 75}
Use update()
method if you want to modify instead of getting a new dictionary.
>>> marks_1.update(marks_2)
>>> marks_1
{'Rahul': 86, 'Ravi': 100, 'Rohit': 78, 'Jo': 89, 'Joe': 75}
The keys()
and values()
dictionary methods return set-like objects, but with insertion order maintained. You get a set object as output when you apply set operators on these objects.
>>> marks_1 = {'Rahul': 86, 'Ravi': 92, 'Rohit': 75}
>>> marks_2 = {'Jo': 89, 'Rohit': 78, 'Joe': 75, 'Ravi': 100}
# union of keys
>>> marks_1.keys() | marks_2.keys()
{'Rohit', 'Rahul', 'Ravi', 'Jo', 'Joe'}
# common keys
>>> marks_1.keys() & marks_2.keys()
{'Ravi', 'Rohit'}
# difference: keys not present in the other dict
>>> marks_1.keys() - marks_2.keys()
{'Rahul'}
>>> marks_2.keys() - marks_1.keys()
{'Jo', 'Joe'}
# symmetric difference: union of above two differences
>>> marks_1.keys() ^ marks_2.keys()
{'Jo', 'Joe', 'Rahul'}
Video demo:
See also my 100 Page Python Intro ebook.