05. Mappings dictionaries

The third category of Python collections is mappings. A mapping is a mutable unordered collection of key-value pairs. Programmers use mappings as associative arrays, lookup tables and hash tables.


To declare a dictionary, use the dict keyword.

>>> dict((('A', 'adenine'),
...    ('C', 'cytosine'),
...    ('G', 'guanine'),
...    ('T', 'thymine')
...    ))

Another way to create a dictionary is between curly braces.

>>> {'A': 'adenine', 'C': 'cytosine', 'G': 'guanine', 'T': 'thymine'}
{'A': 'adenine', 'C': 'cytosine', 'G': 'guanine', 'T': 'thymine'}

Dictionary Operations

The most basic operatiosn of dictionaries act like any other sequence or list, with brackets and indices. Assume we have a dictionary d.

Return the value at key.
d[key] = value
Set (or replace) new key with value.
d[key] += -= *= /= //= %= **
Augmented assignment operators work on dictionaries as well.
del d[key]
Delete a particular key from the dictionary.

Dictionary functions

Here are a list of methods used with dictionaries. As an example, we will use a dictionary d with a key-value pairing. Any default values (what is returned in case a value is not found) will be denoted as dflt.

d.get(key[, dflt])
Get the value that corresponds to the key.
No error if d does
d.setdefault(key[, dflt])
If key exists, do nothing. If not, set to dflt.
d.pop(key[, dflt]
For each key in d,
Returns sequence of keys in d.
Returns sequence of values in d.
Returns a sequence containing (key, value) tuples in d.

Learn to be a Pythonista!

Introducing Python

Learn to be a Pythonista! Try Python

Easy to understand and fun to read, Introducing Python is ideal for beginning programmers as well as those new to the language. Author Bill Lubanovic takes you from the basics to more involved and varied topics, mixing tutorials with cookbook-style code recipes to explain concepts in Python 3. End-of-chapter exercises help you practice what you learned.

$ Check price
39.9939.99Amazon 4.5 logo(37+ reviews)

More Python resources

Aching back from coding all day?

Foam Seat Cushion

Aching back from coding all day? Try Back Problems

This foam seat cushion relieves lowerback pain, numbness and pressure sores by promoting healthy weight distribution, posture and spine alignment. Furthermore, it reduces pressure on the tailbone and hip bones while sitting. Perfect for sitting on the computer desk for long periods of time.

$ Check price
99.9599.95Amazon 4.5 logo(9,445+ reviews)

More Back Problems resources