Janani Ethirraj
Janani Ethirraj

Reputation: 37

How can I iterate through the keys of a dictionary based on condition?

dic = {'a': 1, 'b': 2, 'c': 3}

def iteration(reg=None):
    for k in dic.keys():
        print('x')

iteration(reg='a')
iteration(reg='all')

I am trying to loop through the keys in a dictionary on two different conditions, one when the key is equal to a specific value and the other one is through all keys by denoting 'all' to the argument of the function.

I can go through the first condition by using if k == 'a' (example) but not sure what to pass for the second condition

Upvotes: 0

Views: 3433

Answers (2)

Janani Ethirraj
Janani Ethirraj

Reputation: 37

Thank you all for your answers. I understand that this was a very particular case which did not make sense to a lot of them. But I happened to have the need to do exactly as described in the original question.

I was able to figure out a way to do it and this is how I did it.


def iteration(reg, regDict):
   string1 = 'all'
   if reg.casefold() == string1.casefold():
       reglist = [*regDict]
   else:
       reglist = [reg]

for k in reglist:
   do this

Upvotes: 0

Lucas Roy
Lucas Roy

Reputation: 133

You can do this with the filter function and a lambda expression:

for key in filter(lambda k: k == "a", dic):
    print("x")

You can use this method to filter several things depending on the function you pass into filter, in my example I am filtering out every key that does not equal "a". You can use it to make a wrapper that has the functionality you specify by using a check like so:


def iteration(dic, func="all"):
    return filter(func, dic) if func != "all" else filter(None, dic)

for key in iteration(dic, lambda k: k == "a"):
    print("x")

Upvotes: 1

Related Questions