user1106770
user1106770

Reputation: 1449

Python: using only certain keys in a dictionary for a for-loop

Another python-dictionary question :)

here's my dictionary:

mydict = {key1: valueA, key2: valueA, key3: valueB, key4: valueA,
key5: valueA, key6: valueB, key7: valueB, key8: valueA, key9: valueB}

now i want to iterate through the dictionary only for the key-value-pairs of key4, key5, key6 and key7 and check if the value is valueB. i hope it is possible to understand what i mean..

i want to create a for-loop, and only if the value of key4 is valueB, the content of the loop should be executed, then, if the value of key5 is valueB, it should be executed again, and so on. thanks in advance

Upvotes: 4

Views: 6481

Answers (4)

Dat
Dat

Reputation: 5853

You can also create a set of ignored_keys and then just remove those keys before iteration.

for key in mydicts.keys() - ignore_keys:
    value = mydict[key]
    ....

Upvotes: 1

Karl Knechtel
Karl Knechtel

Reputation: 61643

"from key4 to key7" is not a meaningful concept. A dictionary is fundamentally unordered. There is no sensible way to say that one key comes before or after another.

Determine all the keys you want to check, and check them.

Upvotes: 6

Tom Whittock
Tom Whittock

Reputation: 4230

for key in [key4, key5, key6, key7]:
    if mydict[key] == valueB:
        pass # do stuff here

Upvotes: 12

WeaselFox
WeaselFox

Reputation: 7400

for key in ["key4","key5","key6","key7"]:
   if mydict[key] == valueB :
      #do what you want

Upvotes: 1

Related Questions