Why does dict(k=4, z=2).update(dict(l=1))
return None
? It seems as if it should return dict(k=4, z=2, l=1)
? I'm using Python 2.7 should that matter.
Asked
Active
Viewed 8,548 times
8

Martijn Pieters
- 1,048,767
- 296
- 4,058
- 3,343

raster-blaster
- 131
- 1
- 4
-
Why are people voting this down? to me it was very beneficial. – Steinfeld Sep 07 '16 at 07:12
-
**See also:** https://stackoverflow.com/questions/1452995/why-doesnt-a-python-dict-update-return-the-object – dreftymac Jul 02 '18 at 23:18
3 Answers
18
The .update()
method alters the dictionary in place and returns None
. The dictionary itself is altered, no altered dictionary needs to be returned.
Assign the dictionary first:
a_dict = dict(k=4, z=2)
a_dict.update(dict(l=1))
print a_dict
This is clearly documented, see the dict.update()
method documentation:
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return
None
.

Martijn Pieters
- 1,048,767
- 296
- 4,058
- 3,343
-
-
@raster-blaster: The method alters the dictionary it operates on. It does not return the altered dictionary. – Martijn Pieters Aug 03 '13 at 22:16
-
Oh shoot, I see. Seems rather obvious now. Thank you very much. As a sidenote, I think you meant a_dict instead of dict on the second line. – raster-blaster Aug 03 '13 at 22:18
-
Tried doing that, it's telling me to wait 7 minutes, will do it asap. – raster-blaster Aug 03 '13 at 22:22
3
dict.update()
method does update in place. It does not return the modified dict, but None
.
The doc says it in first line:
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

Rohit Jain
- 209,639
- 45
- 409
- 525
3
For completion's sake, if you do want to return a modified version of the dictionary, without modifying the original you can do it like this:
original_dict = {'a': 'b', 'c': 'd'}
new_dict = dict(original_dict.items() + {'c': 'f', 'g': 'h'}.items())
Which gives you the following:
new_dict == {'a': 'b', 'c': 'f', 'g': 'h'}
original_dict == {'a': 'b', 'c': 'd'}

goibhniu
- 110
- 5