Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: 'if not any' using a dictionary

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'.

like image 932
user1106770 Avatar asked Dec 06 '22 17:12

user1106770


2 Answers

if you have a list of keys you want to check, use a generator expression:

if not any(myDict[key] for key in myKeys):
like image 179
Simon Bergot Avatar answered Dec 09 '22 15:12

Simon Bergot


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'] 
like image 26
unwind Avatar answered Dec 09 '22 16:12

unwind