../_images/search-banner22.png

Dictionaries

A python dictionary stores information as key-value pairs. When a key is provided Python returns the value associated with the key. The keys are unique. A dictionary doesn’t guarantee the order of elements.

Convert two lists into a dictionary (with zip)

keys = ['a', 'b', 'c']
values = [1, 2, 3]
dct = dict(zip(keys, values))

>>> dct
{'a': 1, 'b': 2, 'c': 3}

Convert two lists into a dictionary (with dict comprehension)

keys = ['a', 'b', 'c']
values = [1, 2, 3]
dct = {keys[i]: values[i] for i in range(len(keys))}

>>> dct
{'a': 1, 'b': 2, 'c': 3}

Looping through all key-value pairs

dct = {'key1': 'val1', 'key2': 'val2'}
for key, value in dct.items():
    print(key, value)

# Output
key1 val1
key2 val2

Looping through all the keys

dct = {'key1': 'val1', 'key2': 'val2'}
for key in dct.keys():
    print(key, dct[key])

# Output
key1 val1
key2 val2

Looping through all the values

dct = {'key1': 'val1', 'key2': 'val2'}
for value in dct.values():
    print(value)

# Output
val1
val2

Removing key-value pair

# remove the element with key `key` of dictionary `dct`
del dct['key']

Merging two dictionaries

# in Python 3.5+ (using double asterisk operator **)
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
# merge into new dictionary `z`
z = {**x, **y}

>>> z
{'a': 1, 'b': 3, 'c': 4}

# older Python versions
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
# merge into new dictionary `z`
z = x.copy()
z.update(y)

>>> z
{'a': 1, 'b': 3, 'c': 4}

Dictionary comprehension

# create a new dict switching keys and values
# of existing dictionary `dct`
{v: k for (k, v) in dct.items()}

# same with

new_dct = {}
for k, v in dct.items():
    new_dct[v] = k

Update a dictionary’s keys with comprehension

dct = {1: 'a', 2: 'b', 3: 'c'}
# create a new dictionary with updated keys
new_dct = {k*5: v for (k, v) in dct.items()}

>>> new_dct
{5: 'a', 10: 'b', 15: 'c'}