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 trialMark Chesney
11,747 Pointswarning: using any() and all() on dictionaries
I started writing out a question, then found the answer, so now I'm just typing an FYI:
any()
and all()
are great because they work on lists, sets and tuples, just as you'd expect them to. one warning about dictionaries is that they don't work as expected (or as I'd expected). Example:
dict1 = {'a': True, 'b': False}
# >>> any(dict1)
# True, expected
# >>> all(dict1)
# True, NOT as expected
1 Answer
Mark Chesney
11,747 PointsAs it turns out, any()
and all()
evaluate truthiness based on whether the dictionary is empty or not:
dict2 = dict([])
# >>> any(dict2)
# False, consistent with observation above
# >>> all(dict2)
# True, NOT consistent
wondering would anyone explain the latter case? (does it matter much?)