[Python] Python dictionary comprehension filtering

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    I have a list of dictionaries:

    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"
    }
    ]


    I want to filter them by IMDB > 5.5 :

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


    which outputs:

    [{'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?

    Continue reading...

Compartilhe esta Página