[英]How to call get() on dictionary with indexes?
I have an array of dictionaries but i am running into a scenario where I have to get the value from 1st index of the array of dictionaries, following is the chunk that I am trying to query. 我有一个字典数组,但是我遇到一种情况,我必须从字典数组的第一个索引中获取值,以下是我要查询的块。
address_data = record.get('Rdata')[0].get('Adata')
This throws the following error: 这将引发以下错误:
TypeError: 'NoneType' object is not subscriptable
I tried following: 我尝试了以下操作:
if record.get('Rdata') and record.get('Rdata')[0].get('Adata'):
address_data = record.get('Rdata')[0].get('Adata')
but I don't know if the above approach is good or not. 但我不知道上述方法是否有效。
So how to handle this in python? 那么如何在python中处理呢?
Edit: 编辑:
"partyrecord": {
"Rdata": [
{
"Adata": [
{
"partyaddressid": 172,
"addressid": 142165
}
]
}
]
}
Your expression assumes that record['Rdata']
will return a list with at least one element, so provide one if that isn't the case. 您的表达式假定
record['Rdata']
将返回一个包含至少一个元素的列表,因此,如果不是这样,请提供一个。
address_data = record.get('Rdata', [{}])[0].get('Adata')
Now if record['Rdata']
doesn't exist, you'll still have an empty dict
on which to invoke get('Adata')
. 现在,如果
record['Rdata']
不存在,您仍然会有一个空的dict
在其上调用get('Adata')
。 The end result will be address_data
being set to None
. 最终结果将是
address_data
设置为None
。
(Checking for the key first is preferable if a suitable default is expensive to create, since it will be created whether get
needs to return it or not. But [{}]
is fairly lightweight, and the compiler can generate it immediately.) (检查的关键第一优选的是一个合适的默认是昂贵的创建,因为它会被创建是否
get
需要返回与否,但[{}]
是相当轻便的,编译器可以立即生成它。)
You might want to go for the simple, not exciting route: 您可能想采用简单但不令人兴奋的路线:
role_data = record.get('Rdata')
if role_data:
address_data = role_data[0].get('Adata')
else:
address_data = None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.