-1

How to iterate only selected key in a python dictionary?

    for k, v in myDict:
        print ('key = {}'.format(k))
        print ("value = {}".format(v))

This will print out all keys and its values. Lets say I only want key1, key2 and key5, and their values, any idea?

Thank you

hellojoshhhy
  • 855
  • 2
  • 15
  • 32
  • 1
    Then you should use if statement in the loop to check for that, there is no such thing as "looping over some part of the collection" unless you use filter. – Ali Beyit Mar 11 '20 at 10:24
  • @Ali Well… `for k, v in (i for i in myDict.items() if i[0] in ('key1', ...)):` – deceze Mar 11 '20 at 10:25
  • @deceze so O(n^2) is better than O(log(n)) you say? :) Even though your answer looks like a one liner very clean looking code, in reality it is just slower than checking the condition with if in a loop. – Ali Beyit Mar 11 '20 at 11:10
  • @Ali It's not `O(n^2)`, it's a generator expression… – deceze Mar 11 '20 at 11:15
  • New day new information for me then sir ;) well played – Ali Beyit Mar 11 '20 at 11:16

1 Answers1

1

With a simple if statement.

Note : don't forget .items() to iterate over keys + values in a dictionary

myDict = {
    "key1": 3,
    "key2": 2,
    "key3": 5,
    "key4": 8,
    "key5": 1,
    "key6": 4
}
desired_keys = ["key1", "key2", "key5"]
for k, v in myDict.items():
    if k in desired_keys:
        print ('key = {}'.format(k))
        print ("value = {}".format(v))

Output :

key = key1
value = 3
key = key2
value = 2
key = key5
value = 1
Phoenixo
  • 2,071
  • 1
  • 6
  • 13