[Python] How can I efficiently map and update frequencies of nested items using dictionaries...

Discussão em 'Python' iniciado por Stack, Novembro 25, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on a small DSA practice problem involving frequency counting, but with a twist.
    I have a list of tuples where each tuple represents a (category, item). Example:

    data = [
    ("fruit", "apple"),
    ("fruit", "banana"),
    ("veg", "carrot"),
    ("fruit", "apple"),
    ("veg", "carrot"),
    ("veg", "tomato"),
    ]


    I want to build a dictionary that looks like this:

    {
    "fruit": {"apple": 2, "banana": 1},
    "veg": {"carrot": 2, "tomato": 1}
    }



    I can do this with nested loops or by checking keys manually, but my code feels messy.

    Is there a cleaner or more Pythonic way to build and update a nested dictionary like this? Bonus points if it handles missing keys gracefully without throwing KeyErrors.

    Continue reading...

Compartilhe esta Página