Alex Klinghoffer
Alex Klinghoffer

Reputation: 369

Python- How do I compare a key's value in an IF statement in a FOR loop on a list of dictionaries?

I've shortened it for the purposes of this question, but the code looks like this:

total1=0
total2=0
total3=0
score1=20
score2=30
score3=40


players = [{'user': 'Player1', 'total': total1, 'score': score1},
{'user': 'Player2', 'total': total2, 'score': score2},
{'user': 'Player3', 'total': total3, 'score': score3}]

for i in players:
    if players[i]['score'] <= 30:
        ***code goes here***

I get this TypeError: list indices must be integers, not dict

How do I say "If the value of each players score is <= 30"?

If I just write print players[0]['score'] I get 20. If I write print players[1]['score'] I get 30, but why can't I put it in a for loop and have "i" be the number?

Thanks in advance!

Upvotes: 1

Views: 4245

Answers (3)

david king
david king

Reputation: 758

In this loop:

for i in players:
    if players[i]['score'] <= 30:
        ***code goes here***

i is a the dictionary returned from the list, not the index into the list. What it looks like you want is:

for i, player in enumerate(players):
    if player['score'] <= 30:
        ***code goes here***

Or even:

for player in players:
    if player['score'] <= 30:
        ***code goes here***

if you don't need the index later

Upvotes: 0

diegueus9
diegueus9

Reputation: 31542

The first "for" iterates over the list 'players', so each element is the dictionary:

for player in players:
    if player['score'] <= 30:
        ...

Upvotes: 3

Vlad
Vlad

Reputation: 18633

When you iterate over the list, each i is an element of the list, so replace players[i] with i.

Upvotes: 0

Related Questions