Assume that the dictionary is dics = {0: ‘a’, 1: ‘B’, ‘C’: 3}
1. Take values from the dictionary. Do not want to handle exceptions when the key does not exist
[method] dics get(‘key’, ‘not found’)
[example]
image
[explanation] when the key ‘key’ does not exist, print ‘not found’ (i.e. the information to be handled). When it exists, output the key value.
[other treatment plan I]
if key in dics:
print dics[key]
else:
print 'not found!!'
[other treatment plan II]
try:
print dics[key]
except KeyError:
print 'not found'
example:
image
2. Take values from the dictionary and delete them if found; Do not want to handle exceptions when the key does not exist
[method] dics pop(‘key’, ‘not found’)
[example]
image
[explanation] when the key ‘key’ does not exist, print ‘not found’ (i.e. the information to be processed). When the key exists, output the key value and remove the key.
3. Add an entry to the dictionary. If it does not exist, specify a specific value; If it exists, forget it.
[method] DIC setdefault(key, default)
[example]
image
- update
a = {‘a’:1, ‘b’:2}
a.update({‘c’:3})
a
{‘a’: 1, ‘c’: 3, ‘b’: 2}
a.update({‘c’:4})
a
{‘a’: 1, ‘c’: 4, ‘b’: 2}