Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test the value of all items in a container?

Let's say I have a container such as a dictionary or a list. What is the Python way to test if all of the values of the container are equal to a given value (such as None)?

My naive implementation is to just use a boolean flag like I was taught to do in C so the code could look something like.

a_dict = {
    "k1" : None,
    "k2" : None,
    "k3" : None
}

carry_on = True
for value in a_dict.values():
    if value is not None:
        carry_on = False
        break

if carry_on:
    # action when all of the items are the same value
    pass

else:
    # action when at least one of the items is not the same as others
    pass

While this method works just fine, it just doesn't feel right given how wonderfully Python handles other common patterns. What is the proper way to do this? I thought perhaps that the builtin all() function would do what I wanted but it only tests the values in a boolean context, I would like to compare against an arbitrary value.

like image 988
Michael Leonard Avatar asked Jan 01 '26 14:01

Michael Leonard


1 Answers

You can still use all if you add in a generator expression:

if all(x is None for x in a_dict.values()):

Or, with an arbitrary value:

if all(x == value for x in a_dict.values()):

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!