【发布时间】: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