TIC-FLY
TIC-FLY

Reputation: 173

Delete a dictionary item based on a value from a list iteration

I have tried the following:

losers = ['e', 'b']
candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
for i in losers:
    del candidates_and_fp_votes[losers[i]]
print(candidates_and_fp_votes)

This just returns the error:

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

I would like to iterate over losers and delete every item in candidates_and_fp_votes which has a key in losers

I expect an output of:

{'a': 24, 'c': 17, 'd': 23}

How can I solve this problem?

Thanks in advance.

Upvotes: 1

Views: 47

Answers (4)

Bondrak
Bondrak

Reputation: 1590

your index i is a string, not an integer. You could do something like this:

losers = ['e', 'b']

candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}

for i in losers:

     if i in candidates_and_fp_votes:
          del candidates_and_fp_votes[i]

print(candidates_and_fp_votes)

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71451

You can use dictionary comprehension:

losers = ['e', 'b']
candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
final_dict = {a:b for a, b in candidates_and_fp_votes.items() if a not in losers}

Output:

{'a': 24, 'c': 17, 'd': 23}

Upvotes: 1

PeterH
PeterH

Reputation: 868

When you are iterating over an object (in this case a list called 'losers') the variable i is actually the data in the object not the index of the data like you might see in other languages (c/c++). So in the first iteration of the for loop i == 'e' then the second i == 'b' then the loop would end because there is no more data.

So all you need to do is change losers[i] to just i:

del candidates_and_fp_votes[i]

Here is the complete code with the line fixed.

losers = ['e', 'b']
candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
for i in losers:
    del candidates_and_fp_votes[i]
print(candidates_and_fp_votes)

Upvotes: 1

Barmar
Barmar

Reputation: 780869

i is the list element, not an index. It should be:

del candidates_and_fp_votes[i]

or it should be:

for i in in range(len(losers)):

if you really want the indexes for some reason.

Upvotes: 2

Related Questions