Home > Software design >  How would you use len() to find amount of items in a dictionary of lists in JSON?
How would you use len() to find amount of items in a dictionary of lists in JSON?

Time:04-08

Take a look at this example:

 "guy": {
        "coins": 0,
        "tickets": 0,
        "family": "none",
        "friends": 0,
        "enemies": 0,
        "inventory": {
            "boxes": 0,
            "papers": 0
        },
        "fridge": {
            "fruits": ["apple","apple", "banana", "avocado"],
            "vegetables": ["cucumber", "cucumber", "cucumber", "carrot"],
            "meat": ["minced", "raw", "cooked"],
            "drinks": ["water", "water", "orange_juice"],
            "other_stuff": ["ice_cubes"],
        },
    }

This is an absolutely random and wild example, but I want you to focus on the "fridge" dictionary. If I wanted to know how many items are in "guy"'s fridge, how would I do so? I tried this:

with open("guys.json", "r") as f:
    data = json.load(f)

print(len(data["guy"]["fridge"]))

and the output (which was expected) was:

5

That makes sense because there is 5 TYPES of items in the fridge, but I want to know how many ITEMS there are, not TYPES! I know, I know, we could do this:

len(data["guy"]["fridge"]["fruits"])   len(data["guy"]["fridge"]["vegetables"])   len(data["guy"]["meat"])   len(data["guy"]["fridge"]["drinks"])   len(data["guy"]["fridge"]["other_Stuff"])

But this is definitely not the best method if you have LOTS of food types in your fridge...

How would you do this differently with much less lines of code?

Can you use a 'for' loop on this? How else can you find out how many items are in my fridge (in this example)? I have a "fridge" with 30 types of items, I won't type all that code if there is an easier alternative! Thanks -

CodePudding user response:

Map the len function to each element of the values, and then add it up!

sum(map(len, data["guy"]["fridge"].values()))

CodePudding user response:

You can use itertools.chain which basically flattens iterables of iterables, in your case the values of the fridge dictionary.

import itertools

len(list(itertools.chain.from_iterable(data["guy"]["fridge"].values())))

# result:
15

CodePudding user response:

You could sum the lengths in a for-loop:

sum([len(i) for i in data["guy"]["fridge"].values()])

ItzTheDodo.

  • Related