mkaz.blog

Python

Dicts

Table of Contents

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():
    print(key)
>>> 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():
    print(val)
>>> 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' }
d.get('k1')
>>> 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.

Published: