** * 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. ** **
.keys and .values>>> d = {'x': 10, 'y': 20}
>>> d
{'x': 10, 'y': 20}
>>> d.keys()
dict_keys(['x', 'y'])
>>> d.values()
dict_values([10, 20])
Use .keys to enter the key in the dictionary,
You can display the values in the dictionary with .values.
◆.update
>>> d = {'x': 10, 'y': 20}
>>> d2 = {'x':1000, 'z': 500}
>>> d.update(d2)
>>> d
{'x': 1000, 'y': 20, 'z': 500}
The value of x has been updated and the value of z has been added.
.get and .pop>>> d = {'x': 1000, 'y': 20, 'z': 500}
>>> d['x']
1000
Of course, if you specify a key with [], the value of that key will be returned.
>>> d = {'x': 1000, 'y': 20, 'z': 500}
>>> d.get('x')
1000
>>> d
{'x': 1000, 'y': 20, 'z': 500}
If you specify the key with .get, you can retrieve the value.
At this time, the contents of d have not changed.
>>> d = {'x': 1000, 'y': 20, 'z': 500}
>>> d.pop('x')
1000
>>> d
{'y': 20, 'z': 500}
You can also retrieve the value using .pop,
Unlike .get, the retrieved data disappears from d.
>>> d = {'x': 1000, 'y': 20, 'z': 500}
>>> d['a']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'a'
>>> d.get('a')
>>> n = d.get('a')
>>> type(n)
<class 'NoneType'>
If you do d ['a'], an error will occur, but
If you use d.get ('a'), it will be NoneType.
◆.clear
>>> d = {'x': 1000, 'y': 20, 'z': 500}
>>> d.clear()
>>> d
{}
Using .clear () clears all the data in the dictionary.
◆del
>>> d = {'x': 1000, 'y': 20, 'z': 500}
>>> del d['x']
>>> d
{'y': 20, 'z': 500}
Of course, del can also be used.
◆in
>>> d = {'x': 1000, 'y': 20, 'z': 500}
>>> 'x' in d
True
>>> 'a' in d
False
With 'x' in d
"Does 'x' exist in d?"
Will be.
Recommended Posts