9.3. Methods, Operators and Functions on Dictionaries

Contrary to strings and lists the ordering of the elements in dictionaries does not matter. Elements are accessed by a unique key rather than by an index number.


It is important to notice that dictionary keys have to be unique and immutable.

Table 9.3 gives an overview of the methods and operations on dictionaries.

Table 9.3. Dictionary methods and operations

Method or OperationAction
d[key]get the value of the entry with key key in d
d[key] = valset the value of entry with key key to val
del d[key]delete entry with key key
d.clear()removes all entries
len(d)number of items
d.copy()makes a shallow copy[a]
d.has_key(key)returns 1 if key exists, 0 otherwise
d.keys()gives a list of all keys
d.values()gives a list of all values
d.items()returns a list of all items as tuples (key,value)
d.update(new)adds all entries of dictionary new to d
d.get(key [, otherwise])returns value of the entry with key key if it exists otherwise returns otherwise
d.setdefaults(key [, val])same as d.get(key), but if key does not exists sets d[key] to val
d.popitem()removes a random item and returns it as tuple

[a] shallow copy (see Section 10.2)