Python Dictionary Beginner's Guide

How to use dict

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 when creating a dictionary with a slightly elaborate structure

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)

Introducing named tuple in addition to collections

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

Sample code

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

Execution result

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

Python Dictionary Beginner's Guide
Python Beginner's Guide (Functions)
Python Beginner's Guide (Introduction)
Python Beginner's Guide (Variables / Arrays)
Python dictionary
[Python] dictionary
Python dictionary
Python for super beginners Python # dictionary type 2 for super beginners
Anaconda: Beginners Guide
[Python] Memo dictionary
[Python] Dictionary (hash)
Beginners practice Python
Python beginner's note
Python Basic Course (7 Dictionary)
Python beginners organize heapsort
Python beginners organize quicksort
Python beginners touch Pytorch (3)
python textbook for beginners
Python3 List / dictionary memo
Python beginners touch Pytorch (1)
Python beginners touch Pytorch (2)
OpenCV for Python beginners
Python list, for statement, dictionary
Create a dictionary in Python
About python beginner's memorandum function
Python3 environment construction (for beginners)
3 Reasons Beginners to Start Python
Python> dictionary / collections> defaultdict () / Counter ()
Python #function 2 for super beginners
Python beginners organize bubble sort
Ruby, Python Module Installation Guide
Basic Python grammar for beginners
Avoid KeyError in python dictionary
100 Pandas knocks for Python beginners
Python for super beginners Python #functions 1
Python #list for super beginners
~ Tips for beginners to Python ③ ~
Python> dictionary> get ()> optional value
Notes on Python and dictionary types
Python
Python Exercise for Beginners # 2 [for Statement / While Statement]
Expansion by argument of python dictionary
Replace dictionary value with Python> update ()
Machine learning summary by Python beginners
Python #index for super beginners, slices
Typing automation notes by Python beginners
<For beginners> python library <For machine learning>
Python #len function for super beginners
Basic grammar of Python3 system (dictionary)
Beginners use Python for web scraping (1)
# 2 Python beginners challenge AtCoder! ABC085C --Otoshidama
Run unittests in Python (for beginners)
Memorandum of beginners Python "isdigit" movement
Beginners use Python for web scraping (4) ―― 1
Python #Hello World for super beginners
python beginners tried to find out
Learn the basics of Python ① Beginners
Python> dictionary> values ()> Get All Values by Using values ()
INSERT into MySQL with Python [For beginners]
[Python] Minutes of study meeting for beginners (7/15)
Convert Python> two value sequence to dictionary