如何使用.get()获取嵌套的字典键值 [英] How to get nested dictionary key value with .get()

查看:86
本文介绍了如何使用.get()获取嵌套的字典键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用简单的字典,例如:

With a simple dictionary like:

myDict{'key1':1, 'key2':2}

我可以放心使用:

print myDict.get('key3')

即使'key3'不存在,也不会抛出任何错误,因为.get()仍然返回None.

and even while 'key3' is not existent no errors will be thrown since .get() still returns None.

现在我将如何使用嵌套键字典实现相同的简单性:

Now how would I achieve the same simplicity with a nested keys dictionary:

myDict={}
myDict['key1'] = {'attr1':1,'attr2':2}

以下内容将显示KeyError:

The following will give a KeyError:

print myDict.get('key1')['attr3']

这将通过:

print myDict.get('key1').get('attr3')

但是它将失败并出现adn AttributeError:'NoneType'对象没有属性'get':

but it will fail with adn AttributeError: 'NoneType' object has no attribute 'get':

print myDict.get('key3').get('attr1')

推荐答案

dict.get 接受其他default参数.如果没有这样的键,则返回value而不是None.

dict.get accepts additional default parameter. The value is returned instead of None if there's no such key.

print myDict.get('key1', {}).get('attr3')

这篇关于如何使用.get()获取嵌套的字典键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆