Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update method of python dictionary did not work

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?

like image 865
allenwang Avatar asked Oct 30 '14 14:10

allenwang


People also ask

How does update work in dictionary Python?

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.

Does Dict update overwrite?

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.

Can we update key in dictionary Python?

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.

Can dictionary values be updated?

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.


1 Answers

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.

like image 138
Henry Keiter Avatar answered Oct 02 '22 16:10

Henry Keiter