Revanth
Revanth

Reputation: 51

Iterate list over a dictionary values and print matching key,value

d1 = {'A' : [1,2], 'B':[2,3,4],'C':[4,1,3,2], 'D':[5,6], 'E':[7,2], 'F':[8,1],'G':[1,3,4,2]}

l1 = [1,2,3,4,5,6,7,8,9]
d ={}

for i in l1:
 for key,value in d1.():
   for j in value:
     if i in value[j]:
       d.setdefault(key,[]).append(i)

Expected output:

but I am getting an error:

ValueError: not enough values to unpack (expected 2, got 1)

To give a gist about what I am trying to accomplish is I have list of links that needs to be checked in template and return the template name along with link.

Here the template name is key & the numbers r links which is value

Thank you in advance

Upvotes: 0

Views: 143

Answers (2)

Dawid Januszkiewicz
Dawid Januszkiewicz

Reputation: 36

I edited my original anwser to match your clarification:

d1 = {'A' : [1,2], 'B':[2,3,4],'C':[4,1,3,2], 'D':[5,6], 'E':[7,2], 'F':[8,1],'G':[1,3,4,2]}
l1 = [1,2,3,4,5,6,7,8,9]
d = []

for i in l1:
    for k, v in d1.items():
        if i in v:
            d.append((k,i))

print(d) outputs:

[('A', 1), ('C', 1), ('F', 1), ('G', 1), ('A', 2), ('B', 2), ('C', 2), ('E', 2), ('G', 2), ('B', 3), ('C', 3), ('G', 3), ('B', 4), ('C', 4), ('G', 4), ('D', 5), ('D', 6), ('E', 7), ('F', 8)]

Upvotes: 1

Nothing special
Nothing special

Reputation: 415

Is this what you intend to do?

d1 = {
'A' : [1,2],
'B':[2,3,4],
'C':[4,1,3,2],
'D':[5,6], 
'E':[7,2], 
'F':[8,1],
'G':[1,3,4,2]}

l1 = [1,2,3,4,5,6,7,8,9]
d ={}

for i in l1:
 for key,value in d1.items():
   for j in value:
     if i is j:
       d.setdefault(key,[]).append(i)
print(d)

Output:

{'A': [1, 2], 'C': [1, 2, 3, 4], 'F': [1, 8], 'G': [1, 2, 3, 4], 'B': [2, 3, 4], 'E': [2, 7], 'D': [5, 6]}

Upvotes: 1

Related Questions