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!

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 Functional Python Functional Workhorses Chaining Functions

warning: 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

As 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?)