Desura
Desura

Reputation: 175

For loops in a dictionary and if statement

Firstly, I have to say that i'm a beginner in python. Then, here is my problem : I have a dictionary like this one :

dic = {} 
dic["a", 1] = 0 
dic["a", 2] = 2 
dic["b", 1] = 5 
dic["b", 2] = 0 
... 

And I want to do a for-loop with this dictionary to test all the keys' pair and find which ones are equivalent to 0 in a if statement. I thought of that :

for [co, l], ch in dic.items(): 
    if [co, l] == 0: 

But the if statement is never true, so I can't do anything. Does anyone could provide me some help, please ?

Thanks

Upvotes: 0

Views: 6176

Answers (3)

[co, l] is the key (or copy of it); it is a list with 2 items, and cannot be equal to 0. Instead you want to test the ch value and then perhaps do something with the key.

dic = {} 
dic["a", 1] = 0 
dic["a", 2] = 2 
dic["b", 1] = 5 
dic["b", 2] = 0 
... 

for [co, l], ch in dic.items(): 
    if ch == 0:
        print("The value for key {}, {} was 0".format(co, l))

Or if you want to iterate by the key:

for key in dic:
    if dic[key] == 0:
        print("The value for key {} was 0".format(key))

Upvotes: 2

woot
woot

Reputation: 7606

[co, l] is never 0. I think you mean to test ch.

for [co, l], ch in dic.items():
...     print [co, l], ch
...
['a', 1] 0
['b', 2] 0
['b', 1] 5
['a', 2] 2

Upvotes: 0

La-comadreja
La-comadreja

Reputation: 5755

As per the comments:

for ch in dic.items():
    if ch == 0:

Upvotes: 0

Related Questions