【问题标题】:How to filter a list in a dictionary by the key and values?如何通过键和值过滤字典中的列表?
【发布时间】:2020-05-21 19:08:41
【问题描述】:

我有一本很大的字典,里面有一个叫做交通的列表。这是我的字典的一个小例子:

{'redlights': [{'id': 32,
'userid': '3',
'time': '2013-09-T17:12:00+05:00',
'calls': 1,
'crossings': '0',
'bad_behaviour': '0',
'senior': False,
'cat': False,
'dog': True,
'hitrun': 'David Williams'},
{'id': 384,

所以,我称它为“你好”作为测试。我想要列表红灯中包含“高级”且值为“假”的所有键。我首先尝试了这种 dict 理解来获取所有带有高级的键:

hello = traffic['redlights']
new = {key: value for key, value in hello.items() if key == senior}

但后来我得到了这个错误:AttributeError: 'list' object has no attribute 'items'

可能是因为它是一个列表,但我不知道如何获取其中包含高级值为 false 的键。它必须在红灯列表中,因为其他列表不相关。我如何在字典理解中做到这一点?

【问题讨论】:

  • hello 不是字典,而是字典列表。 new = [item for item in hello if not item['senior']]
  • 因为['redlights']=["List with dictionary inside"].
  • 那么我在该列表中选择了一本字典,对吧?那为什么我仍然收到该错误?
  • @taaaaavi 因为list 没有名为items 的方法。
  • 因为您在列表上使用字典理解,它本身没有键/值对

标签: python python-3.x dictionary list-comprehension dictionary-comprehension


【解决方案1】:

hello 不是字典,它是(字典)列表,而列表没有 items。您必须遍历列表中的每个字典。 此示例将获取每个带有senior=False 的字典的id

res = [d['id'] for d in hello if not d['senior']]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 2023-01-14
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 2022-12-02
    相关资源
    最近更新 更多