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!

Python Playground

Learn to be a Pythonista! Try Python

Python Playground is a collection of fun programming projects that will inspire you to new heights. You'll manipulate images, build simulations, and interact with hardware using Arduino & Raspberry Pi. With each project, you'll get familiarized with leveraging external libraries for specialized tasks, breaking problems into smaller, solvable pieces, and translating algorithms into code.

$ Check price
29.9529.95Amazon 4 logo(14+ reviews)

More Python resources

Ad