if not any(myList[0:5]):
does this also work with a dictionary instead of a list? I want to check if the first five key-value-pairs of my dictionary all have the value 'False'.
if you have a list of keys you want to check, use a generator expression:
if not any(myDict[key] for key in myKeys):
No, dictionary keys are not ordered. You can't say "the first five keys" of a dictionary and mean something well-defined. You can get a list of the keys, in which case they will of course be ordered in that list, but that doesn't say anything about the "order" in the dictionary itself.
What you can do is check all keys in a list to see if the corresponding value in the dictionary is False
:
the_dict = { "k1": True, "k2": False, "k3": False, "k4": True, "k5": False, "k6": True }
check_keys = ["k1", "k2", "k3", "k4", "k5"]
found = 0
for k in check_keys:
if k in the_dict and not the_dict[k]:
found += 1
print "Found %u False values for the checked keys" % found
Notice that just because there is an order to the key-value pairs in the dictionary literal when initializing the_dict
, that doesn't mean that order somehow remains in the dictionary itself.
If your keys are sortable, you can of course sort them manually and then extract the five first:
>>> print sorted(the_dict.keys()[:5]
['k1', 'k2', 'k3', 'k4', 'k5']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With