Python中访问字典的安全方式

错误做法

author = {
   "first_name": "Jonathan",
   "last_name": "Hsu",
   "username": "jhsu98"
}

# 方式1:报错风险
print(author['middle_initial']) # KeyError: 'middle_initial'

# 方式2:冗长
try:
   print(author['username'])
except KeyError as e:
   print(e) # 'username'

# 方式3:冗长
if 'username' in author:
   print(author['username'])

正确做法

1. 当只有访问需求时,如下:

print(author.get('username')) # jhsu98
print(author.get('middle_initial', 'dda')) # 默认值可选,若没有指定,默认为None

2. 当访问的key不存在时,希望将该key及其默认value也加入字典,如下:

print(author.setdefault('username')) # jhsu98
print(author.setdefault('middle_initial', None)) # None

print(author)
"""
{
  'first_name': 'Jonathan',
  'last_name': 'Hsu',
  'username': 'jhsu98',
  'middle_initial': None
}
"""

 

————————————————

参考文献

https://medium.com/better-programming/stop-using-square-bracket-notation-to-get-a-dictionarys-value-in-python-c617f6ea15a3

你可能感兴趣的:(Python中访问字典的安全方式)