[英]Pythonic way to access keys of sub dicts
我经常使用嵌套的字典(例如从json.loads()
创建),有时更深层次的字典会有所不同。 我想找到一种更优雅的Pythonic方式来访问子字典,而无需使用很多嵌套的if
语句。
data = some_func()
if 'network_data' in data:
print "\n## IP Info"
if 'hostname' in data['network_data']:
print "- Hostname: %s" % data['network_data']['hostname']
if 'org' in data['network_data']:
print "- Org: %s" % data['network_data']['org']
if 'city' in data['network_data'] and 'country' in data['network_data'] and 'region' in data['network_data']:
print "- Location: %s, %s, %s" % (data['network_data']['city'],
data['network_data']['country'],
data['network_data']['region'])
(针对其他可能的下标重复该if
语句的各种版本,甚至可能更深入)。
我知道字典的.get()
函数,但是随后遇到了一些中级字典不存在的问题:
ddos = []
for each in vcdb:
variety = each.get('action').get('hacking').get('variety')
if 'DoS' in variety:
ddos.append(each)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-21-40616b7d85d0> in <module>()
1 ddos = []
2 for each in vcdb:
----> 3 variety = each.get('action').get('hacking').get('variety')
4 if 'DoS' in variety:
5 ddos.append(each)
AttributeError: 'NoneType' object has no attribute 'get'
dict.get
接受default
参数,您可以像这样利用它
variety = each.get('action', {}).get('hacking', {}).get('variety', {})
因此,即使在子字典中未找到后续键,它也会返回一个空字典,而不是失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.