Resolved an error problem when Python obtained a value that did not exist in the dictionary dict
- 2020-12-20 03:39:19
- OfStack
Description: In Python2.7, if you want to get a value from the dictionary, but the value may not exist, you should add the following sentence:
Here's an example:
t= {}
if t.get('1'): # right: This through key It's a good way to ask if it exists
print(t['1'])
print('right')
if t['1']: # wrong: This direct check to see if there is an error because it will be called before the check
print(t['1'])
Additional notes:
dict.get(key, default=None) Method details:
Parameters:
key -- This is the Key to be searched in the dictionary.
default -- This is the Value to be returned in case key does not exist.
If default is not specified and no value is found, None is returned