首页 > 解决方案 > 如何过滤列表中嵌套字典中的值?

问题描述

我有这样的内容结构:

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

标签: pythonlistdictionarynested-loops

解决方案


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']

推荐阅读