** * This article is from Udemy "[Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style](https://www.udemy.com/course/python-beginner/" Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style ")" It is a class notebook for myself after taking the course of. It is open to the public with permission from the instructor Jun Sakai. ** **
dict_for
d = {'x': 100, 'y': 200}
for v in d:
print(v)
result
x
y
With such code, only the key is printed. I want to print not only the key but also the value.
.items
methoddict_for
d = {'x': 100, 'y': 200}
for k, v in d.items():
print(k,':', v)
result
x : 100
y : 200
By using .items ()
, if you prepare two variables, key and value will be assigned to each.
To find out how it works, try printing d.items ()
.
dict_for
d = {'x': 100, 'y': 200}
print(d.items())
# for k, v in d.items():
# print(k,':', v)
result
dict_items([('x', 100), ('y', 200)])
You can see that a list of tuples is returned in the d.items ()
part.
This shows that this tuple is unpacked and assigned to two variables.
Recommended Posts