Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new dict by updating an existing one

I want to create a new dictionary, by updating an existing one. This behaves as supposed:

x = {'a': 1}
x.update({'a': 2})

But why does the following results in a NoneType?

({'a': 1}).update({'a': 2})
like image 528
frosch03 Avatar asked Nov 03 '25 19:11

frosch03


1 Answers

All in-place operations in the Python standard library return None, dict.update() is no exception.

You cannot create a dict literal and call .update() on that and expect it to return the updated dict object, no.

You essentially are doing this:

tmp = {'a': 1}
result = tmp.update({'a': 2})
del tmp

and expect result to be the dictionary.

You could use:

dict({'a': 1}, **{'a': 2})

and get a merged dictionary, however. Or, for a more practical looking version:

copy = dict(original, foo='bar') 

creating a copy of a dictionary plus setting some extra keys (replacing any previous value for that key).

In Python 3.5 and newer you’d use:

copy = {**original, 'foo': 'bar'}
like image 124
Martijn Pieters Avatar answered Nov 06 '25 09:11

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!