[Python] Removing elements based on nested dictionary values

Discussão em 'Python' iniciado por Stack, Abril 15, 2025.

  1. Stack

    Stack Membro Participativo

    I have a complex nested dictionary structure and I need to remove elements based on the values in a nested dictionary. My dictionary looks like this:

    my_dict = {
    'item1': {'name': 'Apple', 'price': 1.0, 'category': {'id': 1, 'name': 'Fruit'}},
    'item2': {'name': 'Banana', 'price': 0.5, 'category': {'id': 1, 'name': 'Fruit'}},
    'item3': {'name': 'Carrot', 'price': 0.75, 'category': {'id': 2, 'name': 'Vegetable'}},
    'item4': {'name': 'Broccoli', 'price': 1.5, 'category': {'id': 2, 'name': 'Vegetable'}}
    }


    I want to filter this dictionary to only include items belonging to the 'Fruit' category. I tried the following code:

    new_dict = {}
    for key, value in my_dict.items():
    if value['category']['name'] == 'Fruit':
    new_dict[key] = value
    print(new_dict)


    This works, but I'm wondering if there's a more concise or Pythonic way to achieve this, perhaps using dictionary comprehension or a filtering function like filter().

    Continue reading...

Compartilhe esta Página