How can I check the value of all elements in a container?

Let's say I have a container like a dictionary or a list. What is a Python method for checking if all container values ​​match a given value (for example None

)?

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

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 technique works just fine, it just doesn't feel right, given how nicely Python handles other common patterns. What is the correct way to do this? I thought maybe the inline function all()

would do what I wanted, but it only checks for values ​​in a boolean context, I would like to compare against an arbitrary value.

+3


source to share


1 answer


You can use all

if you add an 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()):

      

+8


source







All Articles