Python dictionaries pass keys and retrieve values. However, it should be noted that an error will occur if the entry corresponding to the specified key is not in the dictionary.
keyerror.py
# -*- coding:utf-8 -*-
import traceback
dct = {"ham": 100, "jam": 300} #There is no egg.
try:
#Since there is no egg, I get a KeyError.
egg = dct["egg"]
except KeyError:
traceback.print_exc()
If you are not guaranteed that the key you specify exists in the dictionary, you can search for it with dict.get and you will not get an error. You can also specify an alternative value.
dictget.py
# -*- coding:utf-8 -*-
dct = {"ham": 100, "jam": 300}
print("dict.get => %s" % dct.get("egg", "orz"))
If it is in the dictionary, it retrieves the contained value, but if it is not, if you want to put an arbitrary value in the dictionary, use dict.setdefault.
dictsetdefault.py
# -*- coding:utf-8 -*-
dct = {"ham": 100, "jam": 300}
#If you want to assign when there is no entry corresponding to the key, setdefault
egg = dct.setdefault("egg", "knuckle")
print("dict.get => %s, egg=%s" % (dct["egg"], egg))
#Since the egg already exists, it will not be overwritten.
egg = dct.setdefault("egg", "mens")
print("dict.get => %s, egg=%s" % (dct["egg"], egg))
Defaultdict is useful when creating a dictionary with a complicated structure. Pass a factory in the constructor that creates an alternative value if there is no entry corresponding to the key. In the following example, a dictionary that holds the value in list is created for each key.
defaultdictusage.py
# -*- coding:utf-8 -*-
from collections import defaultdict
alt = defaultdict(list)
keys = tuple("imagawa")
values = (1, 1, 2, 2, 3, 4, 5)
for k, v in zip(keys, values):
alt[k].append(v)
print(alt)
The defaultdict is in the collections module, but there is another namedtuple in the collections module. You can use this to define an object that is a tuple but also has attribute access.
namedtupleusage.py
# -*- coding:utf-8 -*-
from collections import namedtuple
Role = namedtuple("Role", "user course")
roles = [Role(x, y) for x, y in ((45, 6), (52, 3))]
for role in roles:
print("user=%s, course=%s" % (role.user, role.course))
#Of course, subscript access is also possible.
assert role[0] is role.user and role[1] is role.course
samplecode.py
# -*- coding:utf-8 -*-
import traceback
dct = {"ham": 100, "jam": 300} #There is no egg.
try:
#Since there is no egg, I get a KeyError.
egg = dct["egg"]
except KeyError:
traceback.print_exc()
# dict.If you search with get, no error will occur. You can also specify an alternative value.
print("dict.get => %s" % dct.get("egg", "orz"))
#If you want to assign when there is no entry corresponding to the key, setdefault
egg = dct.setdefault("egg", "knuckle")
print("dict.get => %s, egg=%s" % (dct["egg"], egg))
#Since the egg already exists, it will not be overwritten.
egg = dct.setdefault("egg", "mens")
print("dict.get => %s, egg=%s" % (dct["egg"], egg))
#Defaultdict is useful when creating a dictionary with a complicated structure.
from collections import defaultdict
alt = defaultdict(list)
keys = tuple("imagawa")
values = (1, 1, 2, 2, 3, 4, 5)
for k, v in zip(keys, values):
alt[k].append(v)
print(alt)
#Named tuple namedtuple.
from collections import namedtuple
Role = namedtuple("Role", "user course")
roles = [Role(x, y) for x, y in ((45, 6), (52, 3))]
for role in roles:
print("user=%s, course=%s" % (role.user, role.course))
#Of course, subscript access is also possible.
assert role[0] is role.user and role[1] is role.course
result.txt
Traceback (most recent call last):
File "samplecode.py", line 9, in <module>
egg = dct["egg"]
KeyError: 'egg'
dict.get => orz
dict.get => knuckle, egg=knuckle
dict.get => knuckle, egg=knuckle
defaultdict(<type 'list'>, {'i': [1], 'a': [2, 3, 5], 'm': [1], 'w': [4], 'g': [2]})
user=45, course=6
user=52, course=3
Recommended Posts