Working with Python


The Python dict data structure is an associative array, or key-value pair data structure.

Creating dicts

To specify dictionary looks similar to the JSON object defintion.

d = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3' }

Use dict() constructor to build a dictionary from a list of key-value tuples.

d = dict([ ('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3') ])

Key Exists in Dictionary

Use in to check if a key exists in a dictionary.

d = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3' }
if 'k1' in d:
    print("Key exists")
>>> Key exists

Looping over dict data types

Iterate over keys of a dict

Use .keys() to retrieve a list of keys in a dictionary.

d = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3' }
for key in d.keys():
>>> k1
>>> k2
>>> k3

Iterate over values of a dict

Use .values() to retrieve a list of values in a dictionary.

d = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3' }
for val in d.values():
>>> v1
>>> v2
>>> v3

Iterate over dict using key, value pairs

Use .items() to iterate over both key, value pair.

d = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3' }
for k, v in d.items():
    print(k, v)
>>> k1 v1
>>> k2 v2
>>> k3 iv3

Get item from dict

Use .get() to get an item from the dictionary with a specific key, pass a second argument for default of key does not exist.

d = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3' }
>>> v1
d.get('k4', 0)
>>> 0

Remove item from dict

Use del to delete an item from a dictionary with a specific key, if item does not exist with that key it will raise a KeyError.

d = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3' }
del d['k2']

Merge two dictionaries

As of Python 3.9 (Oct 2020), you can merge two dictionary items using a | operator. The second dictionary specified will overwrite any identical keys that exist in the first.

a1 = { 'a': 'apple', 'b': 'banana' }
a2 = { 'b': 'berry', 'c': 'cherry' }
a1 | a2
>>> { 'a': 'apple', 'b': 'berry', 'c': 'cherry' }

This works quite nicely for having a set of defaults and then merge user preferences over them.

Ordered Dictionaries

The default dict object is unordered, when iterating over a dictionary it will return the keys in arbitrary order, not the same order they are added. Python has a OrderedDict type that you can use to keep the keys in order.

from collections import OrderedDict
od = OrderedDict()
od['a'] = "alpha"
od['b'] = "beta"
od['c'] = "gamma"
for k, v in od.items():
    print(f" {k} => {v}")

Iterating over dictionary in order

Typically I'll want to iterate over a dict in an order, but I often don't use the OrderedDict type, I tend to find it easier to sort the keys and iterate over the keys.

d = {
    'b': 'beta',
    'a': 'alpha',
    'g': 'gamma',
keys = list(d.keys())
for k in keys:
    print(f" {k} -> {d[k]}")

Get Dict Item by Max Value

You can retrieve the maximum item from a dict using the max function and using the .get method to base it on the value instead of the key.

scores = {
    'Alice': 78,
    'Biren': 64,
    'Charlie': 92,
    'David': 54,
    'Eva': 87
max_key = max(scores, key=scores.get)