Python dictionary comprehension filtering

  • A+
Category:Languages

I have a list of dictionaries, for instance :

movies = [ { "name": "The Help", "imdb": 8.0, "category": "Drama" }, { "name": "The Choice", "imdb": 6.2, "category": "Romance" }, { "name": "Colonia", "imdb": 7.4, "category": "Romance" }, { "name": "Love", "imdb": 6.0, "category": "Romance" }, { "name": "Bride Wars", "imdb": 5.4, "category": "Romance" }, { "name": "AlphaJet", "imdb": 3.2, "category": "War" }, { "name": "Ringing Crime", "imdb": 4.0, "category": "Crime" } ] 

I want to filter them by IMDB > 5.5 :

I try this code:

 [ { k:v for (k,v) in i.items() if i.get("imdb") > 5.5 } for i in movies] 

and the output:

[{'name': 'The Help', 'imdb': 8.0, 'category': 'Drama'},  {'name': 'The Choice', 'imdb': 6.2, 'category': 'Romance'},  {'name': 'Colonia', 'imdb': 7.4, 'category': 'Romance'},  {'name': 'Love', 'imdb': 6.0, 'category': 'Romance'},  {},  {},  {}] 

When the IMDB is lower than 5.5, It returns an empty dictionary. any ideas? thank you!

 


A dictionary comprehension is not necessary to filter a list of dictionaries.

You can just use a list comprehension with a condition based on a dictionary value:

res = [d for d in movies if d['imdb'] > 5.5] 

The way your code is written, the dictionary comprehension produces an empty dictionary in cases where i['imdb'] <= 5.5.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: