繁体   English   中英

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM