
Merge Python dictionaries - The difference of double asterisks operation and update method
The unpacking technique (from Python 3.5) enables you to merge some dictionaries.
a = {'apple': 3, 'lemon': 2}
b = {'apple': 15, 'peach': 7}
c = {**a, **b}
print(c) # {'apple': 15, 'lemon': 2, 'peach': 7}
Unpacking, which uses double asterisks, generates multiple pairs so c
has all the pairs in a
and b
. A Python dictionary can't have duplicate keys so the value of apple
is 15 in the merged dictionary.
Example
a = {'apple': 3, 'lemon': 2}
b = {'apple': 15, 'peach': 7}
c = {'lemon': 99}
d = {**a, **b, **c}
print(d) # {'apple': 15, 'lemon': 99, 'peach': 7}
Double asterisks are needed
a = {'apple': 3, 'lemon': 2}
b = {'apple': 15, 'peach': 7}
c = {a, b}
# TypeError: unhashable type: 'dict'
You can't omit asterisks to merge. a
is an object and **a
is the result of unpacking a
. a
itself doesn't mean its pairs.
Merge vs Update
Python dictionary has update
method that differs from merging.
a = {'apple': 3, 'lemon': 2}
b = {'apple': 15, 'peach': 7}
c = a.update(b)
print(c) # None
print(a) # {'apple': 15, 'lemon': 2, 'peach': 7}
print(b) # {'apple': 15, 'peach': 7}
update
returns None and updates the original dictionary while merging with unpacking creates a new dictionary.
Comments
Powered by Markdown