get() A key is specified as an argument, and if the key exists, the corresponding value is returned, and if the key does not exist, None is returned. hatamoto = {'kokugo': 65, 'suugaku': 82}
print(hatamoto.get('kokugo'))
Execution result
65
print(hatamot.get(‘rika’))
Execution result
None
setdefault() Specify "key" as the first argument and "value" as the second argument. If the "key" specified in the first argument does not exist in the target dictionary, a new element will be added.
hatamoto = {'kokugo': 65, 'suugaku': 82}
hatamoto.setdefault('eigo', 70) print(hatamoto) {'kokugo': 65, 'suugaku': 82,'eigo':70}
If the value is omitted with setdefault (), an element with a value of None will be added.
hatamoto = {'kokugo': 65, 'suugaku': 82}
hatamoto.setdefault('eigo') print(hatamoto) {'kokugo': 65, 'suugaku': 82, 'eigo': None}
If the key already exists, specifying the value will not change the original object and no error will occur.
hatamoto = {'kokugo': 65, 'suugaku': 82}
hatamoto.setdefault(kokugo': 62) print(hatamoto) hatamoto = {'kokugo': 65, 'suugaku': 82}
items() The items () method returns the dict_items class.
hatamoto = {'kokugo': 65, 'suugaku': 82} items = hatamot.items() print(items)
dict_items([(kokugo': 65), (suugaku': 82)])
Recommended Posts