mdandr
mdandr

Reputation: 1384

Append a dictionary key to a list depending on the value of the key

While iterating in a for loop, I am trying to append a dictionary item's key to a list if the item has a value of 1.

What I have is:

peeps = {'scoobydoo':0, 'shaggy':0, 'scrappydoo':0, 'velma':1, 'freddy':0, 'daphne':1}
ignore_list = []
for peep in peeps:
    if peep == 1:
        ignore_list.append(peep)
print(ignore_list)

This however does not give me what I would expect:

['velma', 'daphne']

It prints an empty list:

[]

Upvotes: 0

Views: 1062

Answers (3)

neatnick
neatnick

Reputation: 1508

You can iterate through the keys and values of the dictionary to accomplish what you want:

peeps = {'scoobydoo':0, 'shaggy':0, 'scrappydoo':0, 'velma':1, 'freddy':0, 'daphne':1}
ignore_list = []
for key, value in peeps.items():
    if value == 1:
        ignore_list.append(key)
print(ignore_list)

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1122312

You didn't check for the value, only for the key itself.

Check the value by accessing it:

for peep in peeps:
    if peeps[peep] == 1:
        ignore_list.append(peep)

or loop over both keys and values together:

for peep, peep_value in peeps.items():
    if peep_value == 1:
        ignore_list.append(peep)

You can build the list in one step using a list comprehension here:

ignore_list = [peep for peep, peep_value in peeps.items() if peep_value == 1]

Upvotes: 4

Avinash Raj
Avinash Raj

Reputation: 174706

You're iterating over keys not values. So you need to combine the key with the actual dictionary to check if the value of that corresponding key is equal to 1 or not.

peeps = {'scoobydoo':0, 'shaggy':0, 'scrappydoo':0, 'velma':1, 'freddy':0, 'daphne':1}
ignore_list = []
for peep in peeps:
    if peeps[peep] == 1:
        ignore_list.append(peep)
print(ignore_list)

OR

peeps = {'scoobydoo':0, 'shaggy':0, 'scrappydoo':0, 'velma':1, 'freddy':0, 'daphne':1}
print([key for key,value in peeps.items() if value == 1])

Upvotes: 1

Related Questions