I have two dictionaries.
a = {"ab":3, "bd":4}
b = {"cd":3, "ed":5}`
I want to combine them to {'bd': 4, 'ab': 3, 'ed': 5, 'cd': 3}
.
As this says, a.update(b)
can complete it. But when I try, I get:
type(a.update(b)) #--> type 'NoneType'
Would anyone like to explain it to me why I cannot gain a dict type?
I also tried this, and it did well:
type(dict(a,**b)) #-->type 'dict'
What is the difference between these two methods and why did the first one not work?
The update() method inserts the specified items to the dictionary. The specified items can be a dictionary, or an iterable object with key value pairs.
The Python dictionary offers an update() method that allows us to append a dictionary to another dictionary. The update() method automatically overwrites the values of any existing keys with the new ones.
Python Dictionary update() Method It inserts key/value if it is not present. It updates key/value if it is already present in the dictionary. It also allows an iterable of key/value pairs to update the dictionary. like: update(a=10,b=20) etc.
Values of a Python Dictionary can be updated using the following two ways i.e. using the update() method and also, using square brackets. Dictionary represents the key-value pair in Python, enclosed in curly braces.
The update
method updates a dict in-place. It returns None
, just like list.extend
does. To see the result, look at the dict that you updated.
>>> a = {"ab":3, "bd":4}
>>> b = {"cd":3, "ed":5}
>>> update_result = a.update(b)
>>> print(update_result)
None
>>> print(a)
{'ed': 5, 'ab': 3, 'bd': 4, 'cd': 3}
If you want the result to be a third, separate dictionary, you shouldn't be using update
. Use something like dict(a, **b)
instead, which, as you've already noticed, constructs a new dict from the two components, rather than updating one of the existing ones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With