如何通过键和值过滤字典中的列表?

How to filter a list in a dictionary by the key and values?

我有一本非常大的字典,里面有一个叫做 traffic 的列表。这是我的字典的一个小例子:

{'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,

所以,我把它叫做你好作为测试。我想要列表红灯中的所有键,其中包含 'senior',值为 'False'。我首先尝试了这个 dict comprehension 来获取其中包含 senior 的所有键:

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

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

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

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

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