Search code examples
pythonpython-3.xdictionarylist-comprehensiondictionary-comprehension

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


I got a very big dictionary with lists in it called traffic. Here is a small example of my dictionary:

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

So, I called it hello as a test. I want all the keys within the list redlights that has 'senior' in it with value 'False'. I first tried this dict comprehension to get all the keys with senior in it:

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

But then I got this error: AttributeError: 'list' object has no attribute 'items'

Probably because it's a list, but I don't know how I can get the keys that has senior in it with the value false. It has to be in the redlights list because the other lists are not relevant. How do I do this in a dict comprehension?


Solution

  • hello is not a dictionary, it's a list (of dictionaries) and lists don't have items. You have to iterate over each of the dictionaries in the list. This example will get the id of each dictionary with senior=False.

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