社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python,遍历dictionary对象中的多个列表以查找特定值

n3tl0kr • 5 年前 • 1604 次点击  

通过restapi拉取数据,剩下的就是一个包含多个列表的Dictionary对象。我在其中一个列表中寻找一个非常具体的数据点,但是列表的实际数量因字典中的每个项目而异。

我已经尝试使用索引等手动拉这个字段,但是由于列表不总是在同一个位置,我的头撞在墙上了。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

在本例中,查找包含“标识符”的所有列表。如果这是一个错误,请道歉:)并感谢您抽出时间。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39399
 
1604 次点击  
文章 [ 2 ]  |  最新文章 5 年前
lesliehuang93
Reply   •   1 楼
lesliehuang93    5 年前

我偷偷来水一下,顺便看看IV能不能插入视频。 下面(可能会)是我这个非常菜的PV随便做的蝴蝶~ 重庆时时彩开奖网北京pk10视频床是我自建的,完善以后应该会对论坛里的小伙伴们开放~

skymon
Reply   •   2 楼
skymon    5 年前

这应该有效:

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)
bagerard
Reply   •   3 楼
bagerard    5 年前

据我所知,你需要选择 value 项目中的字段 protocol_parameters 包含name=identifier的。

你可以用 next() 从中查找第一项 协议\参数 符合该条件的列表。见下文:

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