这正是try-except为了:
try:
print(location.raw['address']['town'])
except KeyError:
print(location.raw['address']['city'])
备择方案
一些注重性能的人会说“但是 try-except 很昂贵”。
您可以使用其他一些替代方案:
if 'town' in location.raw['address']: ... else: ...
location.raw['address'].get('town', location.raw['address'].get('city'))
每种方法都有自己的优点和缺点。.get,例如,并不懒惰。location.raw['address'].get('city')将在'town'查找之前进行评估,因此实际上它更加浪费和适得其反。该if-else方法(取决于它的使用方式)可能需要对其中一个键进行两次哈希处理。
我认为将更常见的密钥放在try块中就足够了。
让我们做一些测试:
from timeit import Timer
from random import choice
list_of_dicts = [{choice(('town', 'city')): 1} for _ in range(2000)]
def try_except():
for d in list_of_dicts:
try:
d['town']
except KeyError:
d['city']
def if_else():
for d in list_of_dicts:
if 'town' in d:
d['town']
else:
d['city']
def get():
for d in list_of_dicts:
d.get('town', d.get('city'))
print(min(Timer(try_except).repeat(10, 10)))
print(min(Timer(if_else).repeat(10, 10)))
print(min(Timer(get).repeat(10, 10)))
这输出
0.0053282611981659705
0.0018278721105344786
0.00536558375274554
这意味着在这个包含 2000 个字典的示例中,if-else是最快的(即使它需要对其中一个键进行两次散列),并且try-except和get大致相同。