Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (Retired) Dictionaries Teacher Stats

is this logic of comparing len(value) to a count = 0 variable common in python?

or is it just to make us think?

def favorite_Food(fav):
    fav_count = 0
    favorite = None
    for food, stars in fav.items():
        if len(stars) > fav_count:
            fav_count = len(stars)
            favorite = food
    return favorite.title()

1 Answer

Hi John

Yes, its a common way of comparing the length of a list. if i has a list with fruits and wanted to know the quantity of fruits i would do it like so.See below

fruits = []
fruits.append('bananas')
fruits.append('apples')
fruits.append('mangoes')
fruits.append('grapes')

print(len(fruits)) #this would print 4 

Hi Andreas, Thanks for responding. I'm aware of comparing lists, but this concept was introduced because there is an undetermined number of lists to be considered. So instead of comparing list to list, the concept is comparing the length of the value of a dict, to the count variable. This determines if the current length of the iterated value is the longest value. This bypasses the need to use an empty list for comparison sake. It works, I was just wondering if it was common. It has been a definite mind bender for me :D

The dict to be passed in could look something like:

favorite_foods = {
"pizza": ["*", "*", "*"],
"burgers": ["*", "*"],
"salad": ["*", "*", "*", "*", "*"]
}

favorite_food(favorite_foods )

favorite_food(favorite_foods )