This time it looks easy at first glance, but it's actually deep, How to create a dictionary </ b> is described.
In this article, I will write in the following order. ・ How to create with curly braces ・ How to create with dict () ・ How to create in dictionary comprehension
How to generate with {key: value, key: value, ...}.
d = {'k1': 1, 'k2': 2, 'k3': 3} print(d)
# {'k1': 1, 'k2': 2, 'k3': 3}
The following two methods can be done from Python 3.5, and it seems that not only two but three or more can be done. Also d = {**d1, **d2, 'k5': 5} As it seems, it is possible to combine and add for cleaning. Even if you do this, d1 and d2 seem to remain the same.
d1 = {'k1': 1, 'k2': 2} d2 = {'k3': 3, 'k4': 4}
d = {**d1, **d2} print(d)
# {'k1': 1, 'k2': 2, 'k3': 3, 'k4': 4}
print(d1)
# {'k1': 1, 'k2': 2}
print(d2)
# {'k3': 3, 'k4': 4}
It seems that a dictionary is generated by setting> dict (key = value). An example is shown below.
d = dict(k1=1, k2=2, k3=3) print(d)
# {'k1': 1, 'k2': 2, 'k3': 3}
How to generate from a list of key and value combinations (tuples (key, value), etc.).
d = dict([('k1', 1), ('k2', 2), ('k3', 4)]) print(d)
# {'k1': 1, 'k2': 2, 'k3': 4}
Also, if it is iterable as follows List tuples List of sets (set type) There is no problem with combinations such as.
・ List tuple
d = dict((['k1', 1], ['k2', 2], ['k3', 4])) print(d)
# {'k1': 1, 'k2': 2, 'k3': 4}
・ List of sets (set type)
d = dict([{'k1', 1}, {'k2', 2}, {'k3', 4}]) print(d)
# {1: 'k1', 2: 'k2', 'k3': 4}
Generate a dictionary from the zip function
keys = ['k1', 'k2', 'k3'] values = [1, 2, 3]
d = dict(zip(keys, values)) print(d)
# {'k1': 1, 'k2': 2, 'k3': 3}
You can use the zip () function to create a dictionary from a list of keys and a list of values. Not limited to lists, tuples etc. are OK.
{key: value for arbitrary variable name in iterable object}
l = ['Alice', 'Bob', 'Charlie']
d = {s: len(s) for s in l} print(d)
# {'Alice': 5, 'Bob': 3, 'Charlie': 7}
The difference from the list comprehension is that it is enclosed in {} instead of [], and that the key and value are specified.
To create from a list of keys and values, use the zip () function as well as the constructor dict ().
keys = ['k1', 'k2', 'k3'] values = [1, 2, 3]
d = {k: v for k, v in zip(keys, values)} print(d)
# {'k1': 1, 'k2': 2, 'k3': 3}
For the first time, I learned that there are so many ways to create a dictionary. It's quite interesting. See you next time.
Recommended Posts