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})
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'}
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