Dictionary

In Python a dictionary is used to store a mapping from one set of objects to another.

An entry in a dictionary consists of a key and its associated value. Then, to access the dictionary you can provide a key, and Python will "look up" and return the associated value. Values can be any type of object, but keys must be immutable. This means keys could be integers, strings, or tuples, but not lists, because lists are mutable.

Dictionaries themselves are mutable, so entries can be added, removed, and changed at any time. Note, though, that because entries are accessed by their key, we can't have two entries with the same key.

Basics

To create a dictionary, we place a comma separated list of entries within curly brackets. Each entry is of the form key:value. For example, we could use a dictionary to store the grades various students got on a test:

grades = {'arthur':90, 'belle':60, 'charles':80}

Then, if you wanted to access the grade of a particular student, you can type

grades['charles']

and Python will return 80 (the value we associated with the 'charles' key).

We can also add and change elements this way:

grades['charles'] = 85 # updates the value of charles to 85
grades['doug'] = 70    # adds a new entry

To remove entries we can use

del grades['belle']

Useful Functions

While dictionaries aren't sequences, some of the same functions will work with them.

  • len(d) returns the number of elements in dictionary d.
  • k in d returns True iff d contains an entry with key k.
  • d.copy() returns a copy of d. Because dictionaries can't be sliced, this is the best way to copy them.
  • d.keys() returns only the keys in d in a view (see below).
  • d.values() returns only the values in d in a view.
  • d.items() returns the key/value pairs in d in a view. Each pair is in the form of a tuple.

Views are a special type of object, different from a sequence. They can be iterated over like a sequence, for example:

for key in d.keys(): # loop through the keys of d
    ...
for (key, value) in d.items(): # loop through key/value pairs
    ...

You can also convert them to other types using type conversion functions if you need to, for example:

list(d.keys())    # returns a list of the keys in d
tuple(d.values()) # returns a tuple of the values in d


See Also