python - 如何过滤列表中嵌套字典中的值?
问题描述
我有这样的内容结构:
content = [
{'@type': 'ListItem', 'position': 1,
'item':
{'@type': 'Product', 'url': 'TestSample', 'sku': 'HO6096863EAD7E0PH', 'mpn': 'HO6096863EAD7E0PH', '@id': 'HO6096863EAD7E0PH'}},
{'@type': 'ListItem', 'position': 2,
'item':
{'@type': 'Product', 'url': 'TestSample', 'sku': 'HO5FFFA64882401PH', 'mpn': 'HO5FFFA64882401PH', '@id': 'HO5FFFA64882401PH'}}
]
我需要使用键“url”获取所有值。我使用了这样的循环并且它可以工作,但是如何使它更容易呢?我已经阅读了有关“过滤器”功能的信息,但不确定它是否适合我的情况。
for r in content:
k = r.get('item', {}).get('url')
print(k)
输出应该是:TestSample,TestSample
解决方案
Filter is used for filtering elements from an iterable, you can get elements with matching criteria.
But if you want sub element from the element you can use map function for this.
check below example, here the lambda function will take url from each item and map will apply this lambda function on each dict in your list:
l = list(map(lambda x:x['item']['url'],content))
print(l)
output is:
['TestSample', 'TestSample']
推荐阅读
- sockets - 是否可以使用 TCP 或 UDP 中继 UDP 或 TCP 数据;即混合协议?
- c# - 如何检查 XamDataGrid 中是否存在列?
- r - 双循环以获取 R 中的数据帧(tidyverse)
- javascript - iPhone Safari 平滑滚动问题
- php - 如何从使用 CodeIgniter 的 Web 服务器读取 POST 或 GET 请求
- amazon-web-services - AWS Application Load Balancer SSL 终止与 Apache Docker
- c# - BizTalk WCF-SQL 接收位置开始在多服务器环境中的两个服务器中轮询
- python - 如何矢量化/加速熊猫中的分组/过滤数据?
- excel - 我需要 VBA 代码来单独汇总最后一行数据下方的列
- python - 在 Python 中以交替方式从两个数据框列中提取值