别再用方括号在Python中获取字典的值,试试这个方法
小白学视觉
共 2833字,需浏览 6分钟
·
2022-01-20 06:54
点击上方“小白学视觉”,选择加"星标"或“置顶”
重磅干货,第一时间送达
author = {
"first_name":"Jonathan",
"last_name":"Hsu",
"username":"jhsu98"
}
author = {
"first_name":"Jonathan",
"last_name":"Hsu",
"username":"jhsu98"
}print(author['username']) # jhsu98
print(author['middle_initial']) # KeyError: 'middle_initial'
author = {}try:
print(author['username'])
except KeyError as e:
print(e) # 'username'ifauthor['username']:
print(author['username'])
author = {
"first_name":"Jonathan",
"last_name":"Hsu",
"username":"jhsu98"
}print(author.username)
# AttributeError: 'dict' object has no attribute 'username'
author = {
"first_name":"Jonathan",
"last_name":"Hsu",
"username":"jhsu98"
}print(author.get('username')) # jhsu98
print(author.get('middle_initial', None)) # None
author = {
"first_name":"Jonathan",
"last_name":"Hsu",
"username":"jhsu98"
}print(author.setdefault('username')) # jhsu98
print(author.setdefault('middle_initial', None)) # None
author = {
"first_name":"Jonathan",
"last_name":"Hsu",
"username":"jhsu98"
}print(author.setdefault('middle_initial',None)) # None
print(author)
"""
{
'first_name': 'Jonathan',
'last_name': 'Hsu',
'username': 'jhsu98',
'middle_initial': None
}
""
交流群
欢迎加入公众号读者群一起和同行交流,目前有SLAM、三维视觉、传感器、自动驾驶、计算摄影、检测、分割、识别、医学影像、GAN、算法竞赛等微信群(以后会逐渐细分),请扫描下面微信号加群,备注:”昵称+学校/公司+研究方向“,例如:”张三 + 上海交大 + 视觉SLAM“。请按照格式备注,否则不予通过。添加成功后会根据研究方向邀请进入相关微信群。请勿在群内发送广告,否则会请出群,谢谢理解~
评论