【问题标题】:How to filter values in nested dicts which are in list?如何过滤列表中嵌套字典中的值?
【发布时间】:2021-07-31 21:54:36
【问题描述】:

我有这样的内容结构:

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

【问题讨论】:

  • 为什么对当前的代码不满意?
  • 你的方法有什么问题?您可以使用理解使其更容易:k = [r.get('item', {}).get('url') for r in content]
  • @Sandertjuhh 非常感谢!
  • filter 可以帮助您避免在没有其中一个键的情况下跳过字典,但您也可以在循环中使用简单的if 来做到这一点。

标签: python list dictionary nested-loops


【解决方案1】:

Filter用于从一个iterable中过滤元素,你可以得到符合条件的元素。

但是如果你想要元素中的子元素,你可以使用 map 函数。

查看下面的示例,这里的 lambda 函数将从每个项目中获取 url,而 map 将在列表中的每个 dict 上应用这个 lambda 函数:

l = list(map(lambda x:x['item']['url'],content))
print(l)

输出是:

['TestSample', 'TestSample']

【讨论】:

    【解决方案2】:

    你的意思是map而不是filter

    items = map(lambda x: x.get('item', {}).get('url'), content)
    for item in items:
        print(item)
    

    上面的代码会打印出来:

    TestSample
    TestSample
    

    如果你想要一个filter 的例子:

    filtered = filter(lambda x: 'item' in x and 'url' in x['item'], content)
    items = map(lambda x: x['item']['url'], filtered)
    for item in items:
        print(item)
    

    过滤器的作用是检查 'item' 和 'url' 是否在该字典值中,如果是,则将其添加到结果中,如果不是,则不会添加它。这样您就可以确定filtered 将始终同时拥有itemurl

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-07
      • 2021-11-21
      • 2017-06-17
      • 2012-06-25
      • 2022-07-13
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      相关资源
      最近更新 更多