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

``KeyError: 'd'``

# 第一种解决方法

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

``not exist``

# 第二种解决方法

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

``None``

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

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

# 第三种解决方法

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

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

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

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

# 第四种解决方法

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

class Counter(dict):

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

``None``

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

class Counter(dict):

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

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

# 第五种解决方法

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

``KeyError: 'd'``

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

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

``None``

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

``0``

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

``[]``

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

``KeyError: 'y'``