![](/img/trans.png)
[英]Iterate through nested Dictionary Object and get the value of specific object in Python
[英]Python, iterate through multiple lists in a dictionary object to find a specific value
通過RESTapi提取數據,剩下一個包含多個列表的字典對象。 我正在其中一個列表中尋找非常具體的數據點,但是列表的實際數量隨字典中的每個項目而變化。
我嘗試使用索引等方式手動拉出該字段,但是由於列表並不總是位於同一位置,所以我將頭撞在牆上。 API結果看起來像這樣。
b = [
{'internal': False, 'protocol_parameters': [{'name': 'identifier', 'id': 1, 'value': 'x.x.x.x'}]},
{'internal': False, 'protocol_parameters': [{'name': 'identifier', 'id': 0, 'value': 'y.y.y.y'}, {'name': 'incomingPayloadEncoding', 'id': 1, 'value': 'UTF-8'}]},
{'internal': False, 'protocol_parameters': [{'name': 'incomingPayloadEncoding', 'id': 1, 'value': 'UTF-8'}, {'name': 'identifier', 'id': 0, 'value': 'z.z.z.z'}]}]
for a in b:
c = (a['protocol_parameters'])[0].get('value')
print(c)
當然,由於列表位置不一致,因此無法正確解析,所以我很好奇我是否可以解析字典中的所有列表以查找特定字符串。 無論列表位置如何,我的最終目標都將如下所示。
x.x.x.x
y.y.y.y
z.z.z.z
在本示例中,找到所有包含“標識符”的列表。 抱歉,如果這是一個菜鳥錯誤:),謝謝您的時間。
據我了解,您需要從protocol_parameters
項中選擇包含name = identifier的value
字段。
您可以使用next()
從protocol_parameters
列表中找到與該條件匹配的第一項。 見下文:
records = [{'internal': False, 'protocol_parameters': [{'name': 'identifier', 'id': 1, 'value': 'x.x.x.x'}]},
{'internal': False, 'protocol_parameters': [{'name': 'identifier', 'id': 0, 'value': 'y.y.y.y'}, {'name': 'incomingPayloadEncoding', 'id': 1, 'value': 'UTF-8'}]},
{'internal': False, 'protocol_parameters': [{'name': 'incomingPayloadEncoding', 'id': 1, 'value': 'UTF-8'}, {'name': 'identifier', 'id': 0, 'value': 'z.z.z.z'}]}
]
for record in records:
identifier_param = next((prot_param for prot_param in record['protocol_parameters'] if prot_param['name']=='identifier'), None)
if identifier_param:
print(identifier_param['value'])
版畫
x.x.x.x
y.y.y.y
z.z.z.z
這應該工作:
b = [{'internal': False, 'protocol_parameters': [{'name': 'identifier', 'id': 1, 'value': 'x.x.x.x'}]},
{'internal': False, 'protocol_parameters': [{'name': 'identifier', 'id': 0, 'value': 'y.y.y.y'}, {'name': 'incomingPayloadEncoding', 'id': 1, 'value': 'UTF-8'}]},
{'internal': False, 'protocol_parameters': [{'name': 'incomingPayloadEncoding', 'id': 1, 'value': 'UTF-8'}, {'name': 'identifier', 'id': 0, 'value': 'z.z.z.z'}]}]
for a in b:
c = next(param.get('value') for param in a['protocol_parameters'] if param.get('name')=="identifier")
print(c)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.