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.

Aching back from coding all day?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources

Learn to be a Pythonista!

Learning Python

Learn to be a Pythonista! Try Python

Get a comprehensive, in-depth introduction to the core Python language with this hands-on book. Based on author Mark Lutz's popular training course, this updated fifth edition will help you quickly write efficient, high-quality code with Python. It's an ideal way to begin, whether you're new to programming or a professional developer versed in other languages.

$ Check price
64.9964.99Amazon 4 logo(279+ reviews)

More Python resources