-2

I have this dictionary:

c = {0: [0, 2, 3], 1: [1, 6, 9]}

and I have this list:

f = [1, 0, 6]

and I want to know for every member in f, what is the key in the dictionary c?

Here is the code I am using to achieve this:

for m, n in c.items():
    for k in n:
        for l in f:         
            if k == l:
                print(m)

and I get this result:

0
1
1

but I think the result should be:

1
0
1

What can I do to make the result like what I want it to be?

I really appreciate you help.

Thank you.

o-90
  • 17,045
  • 10
  • 39
  • 63

1 Answers1

3

You are looping over the items of C; iteration over a dictionary takes place in a implementation specific, internal order (see Why is the order in dictionaries and sets arbitrary?). Since you did not also print the k variable, you have no idea what was paired with what.

You'd have to loop over n in the outer loop if you wanted to print things in the same order:

for k in f:
    for m, n in C.items():
        if k in n:
            print m
            break

I adjusted the inner loop to use a list membership test with in, and I used break to stop further searching.

Using dictionaries like this is rather counter-productive. If n is large, consider creating an inverse index instead:

inverse = {}
for m, n in C.items():
    for i in n:
        inverse.setdefault(i, set()).add(m)

then use that to do fast lookups:

for k in f:
    print inverse.get(k, set())

The inverse holds sets of keys for a given value (since there could easily be more than one list in which a value appears).

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • ♦ thanks man. i just run my code in one of those visualize python shell to know how my code run and i just realize my loop is totally wrong. thanks for teaching me something today. – daniel simamora Jan 28 '17 at 12:51