RustyShackleford
RustyShackleford

Reputation: 3677

How to iterate and compare values of keys in list of dictionaries?

I have two dictionaries that look like this:

dict1 = {'id':'a12','key':'value'}
dict2 = [{'id':'a12'},{'id':'a12'}]

How do I iterate through dict2 and compare whether id value matches value in dict1 and append the dictionary in dict2 to a list if there is a match?

I have written this code:

lst=[]
for i in dict2:
    if dict1['id'] == dict2['id']:
        lst.append(i)

I get this error when I run the above code:

TypeError: list indices must be integers or slices, not str

What am I doing wrong in the comparison?

Upvotes: 0

Views: 1104

Answers (2)

matanper
matanper

Reputation: 931

dict2 is array, not dictionary. you need to use the i variable inside the for loop:

lst=[]
for i in dict2:
    if dict1['id'] == i['id']:
        lst.append(i)

Upvotes: 2

PaulProgrammer
PaulProgrammer

Reputation: 17630

Nothing. You are doing nothing wrong in your comparison. The problem is that dict2 is, in fact, an array of dictionaries, so there's no such thing as dict2['id'] -- you're thinking of i['id'].

lst=[]
for i in dict2:
    if dict1['id'] == i['id']:
        lst.append(i)

Upvotes: 1

Related Questions