我有一个像这样的嵌套词典:
mail = {
'data': { 'from': {'text': '123@example.com'}}
# some other entries...
}
我正在尝试使用以下代码复制from
值:
data = mail.get('data')
new_dict['parse']['from'] = data.get('from').get('text')
第二行抛出例外:
AttributeError: 'NoneType' object has no attribute 'get'
奇怪的是,这有时只会发生。如果我在第二行之前添加打印语句,例如:
data = mail.get('data')
print(type(data.get('from')))
new_dict['parse']['from'] = data.get('from').get('text')
错误消失了,我会按预期获得<class 'dict'>
。如果我删除打印语句,则有时可以工作,而有时则会引发错误。代码或数据没有其他任何更改。我使用get()
的原因是在丢失密钥时安全地检索值。
在呼叫data.get('from').get('text')
中,如果data
不包含键'from'
,则将返回None
。 None.get('text')
升高然后您看到的例外,因为 None
对象没有 get
方法(当然(。
这样做的方法是传递比具有get
方法的None
(默认默认值(更好的默认对象。那将是一个空词典, {}
:
data = mail.get('data')
new_dict['parse']['from'] = data.get('from', {}).get('text')