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.

Aching back from coding all day?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources

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

Ad