Python Dictionary Methods

Originally Posted on with tags: python
Last Update on

Some Python code I read yesterday uses dictionary methods copy and update. This prompted me to test those two methods and check all other python dictionary methods.

Here is the code testing the two methods:

>>> d = {'a': 1, 'b': 2, 'c':3}
>>> d
{'a': 1, 'b': 2, 'c': 3}
>>> d1 = d
>>> d['a']=0
>>> d1
{'a': 0, 'b': 2, 'c': 3}
>>> d2 = d.copy()
>>> d['a'] = 4
>>> d1
{'a': 4, 'b': 2, 'c': 3}
>>> d2
{'a': 0, 'b': 2, 'c': 3}
>>> d2.update({'a':4, 'e':5})
>>> d2
{'a': 4, 'b': 2, 'c': 3, 'e': 5}
>>> 

Python official documentation lists dictionary methods on the Built-in Types page. The page has a seciton Mapping Types - dict which lists all dictionary methods. The notable class methods are clear, copy, fromkeys, get, items, keys, pop, popitem, setdefault, update, and values.

I found some interesting online documentation when searching for the topic.

The dictionary is so fundamental in Python and programmers should become familar with those methods.