Operations on Dictionaries

Dictionaries provide a mapping between names and objects. You can apply the following operations to dictionaries:

OperationDescription
x = d[k]Indexing by key
d[k] = xAssignment by key
del d[k]Deletes an item by key
len(d)Number of items in the dictionary

Key values can be any immutable object, such as strings, numbers, and tuples. In addition, dictionary keys can be specified as a comma-separated list of values, like this:

d = { }
d[1,2,3] = "foo"
d[1,0,3] = "bar"

In this case, the key values represent a tuple, making the preceding assignments identical to the following:

d[(1,2,3)] = "foo"
d[(1,0,3)] = "bar"

Get Python: Essential Reference, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.