python keyerror(0)


It’s not the key of the keyboard, it’s the key of the dict
When dict is evaluated, the key does not exist in the key() of dict, and an error is reported

When python reads key and value, if key does not exist, it will trigger KeyError error, as follows:

Python

t = {
    'a': '1',
    'b': '2',
    'c': '3',
}
print(t['d'])

It will appear:

KeyError: 'd'

The first solution
First, test whether the key exists, and then proceed to the next operation, such as:

Python

t = {
    'a': '1',
    'b': '2',
    'c': '3',
}
if 'd' in t:
    print(t['d'])
else:
    print('not exist')

There will be:

not exist

The second solution
Use the built-in get(key[,default]) method dict; if key exists, return its value; otherwise return default; Using this method will never trigger KeyError, as follows:

Python

t = {
    'a': '1',
    'b': '2',
    'c': '3',
}
print(t.get('d'))

There will be:

None

Add default parameter:

Python

t = {
    'a': '1',
    'b': '2',
    'c': '3',
}
print(t.get('d', 'not exist'))
print(t)

There will be:

not exist
{'a': '1', 'c': '3', 'b': '2'}

The third solution
Using dict built-in setdefault(key[,default]) method, if key exists, return its value; Otherwise insert this key, its value is default, and return default; Using this method will never trigger KeyError, as follows:

Python

t = {
    'a': '1',
    'b': '2',
    'c': '3',
}
print(t.setdefault('d'))
print(t)

There will be:

None
{'b': '2', 'd': None, 'a': '1', 'c': '3'}

Add default parameter:

Python

t = {
    'a': '1',
    'b': '2',
    'c': '3',
}
print(t.setdefault('d', 'not exist'))
print(t)

There will be:

not exist
{'c': '3', 'd': 'not exist', 'a': '1', 'b': '2'}

The fourth solution
Add the /___ b> method to the class dict. If key does not exist, it goes to the missing__() method without firing KeyError, e.g.

Python

t = {
    'a': '1',
    'b': '2',
    'c': '3',
}


class Counter(dict):

    def __missing__(self, key):
        return None
c = Counter(t)
print(c['d'])

There will be:

None

Change return value:

Python

t = {
    'a': '1',
    'b': '2',
    'c': '3',
}


class Counter(dict):

    def __missing__(self, key):
        return key
c = Counter(t)
print(c['d'])
print(c)

There will be:

d
{'c': '3', 'a': '1', 'b': '2'}

The fifth solution
Using the collections.defaultdict([default_factory[...]]) object, which is actually inherited from the dict and is actually used with the missing__ __() method, its default_factory argument is passed to the missing__() method,
if default_factory is None, it will be the same as dict, it will trigger KeyError error, as follows:

Python

import collections
t = {
    'a': '1',
    'b': '2',
    'c': '3',
}
t = collections.defaultdict(None, t)
print(t['d'])

There will be:

KeyError: 'd'

But if you really want to return None is not out of the question:

Python

import collections
t = {
    'a': '1',
    'b': '2',
    'c': '3',
}

def handle():
    return None
t = collections.defaultdict(handle, t)
print(t['d'])

There will be:

None

If the default_factory parameter is a data type, it will return its default value, such as:

Python

import collections
t = {
    'a': '1',
    'b': '2',
    'c': '3',
}
t = collections.defaultdict(int, t)
print(t['d'])

There will be:

0

Such as:

Python

import collections
t = {
    'a': '1',
    'b': '2',
    'c': '3',
}
t = collections.defaultdict(list, t)
print(t['d'])

There will be:

[]

Note:
if dict contains dict, key nested to get value, if a middle key0 does not exist, then all the above methods are invalid, and 1 KeyError2 will be triggered:

Python

import collections
t = {
    'a': '1',
    'b': '2',
    'c': '3',
}
t = collections.defaultdict(dict, t)
print(t['d']['y'])

There will be:

KeyError: 'y'

Read More: