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.

Dictionaries

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.

d[key]
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]
d.update(e)
For each key in d,
d.keys()
Returns sequence of keys in d.
d.values()
Returns sequence of values in d.
d.items()
Returns a sequence containing (key, value) tuples in d.

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

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources

Ad