Cootie234 Cootie234 - 1 month ago 12
Python Question

Defining function weeklies(plants_d)


Consider a dictionary,
plants_d
, where the keys are names of plants,
and the values are descriptions of how often to water them. Search
through the entire structure for all plants that need to be watered
"weekly"
, put them into a list,
sort()
the list, and return it.

plants_d
:: dictionary of plant names to watering instructions.

Return value: sorted list of plants that need watering
"weekly"
.

Test cases:

>>> weeklies({'shamrock':'weekly', 'cactus':'monthly', 'rose':'weekly', 'succulent':'biweekly'})
['rose', 'shamrock']

>>> weeklies({'fern':'weekly', 'shamrock':'weekly', 'carnation':'weekly'
['carnation', 'fern', 'shamrock']



I understand that I need to see if the
dict[i]== 'Weekly'
and then add it to a new list but I am not sure how. What I have tried:

def weeklies(plant_d):
plants = {}
for in in plants_d:
if dict{i} == 'weekly':
plants = plants.append(i)
return plants

Answer

You need to replace:

if dict{i} == 'weekly':

with:

if dict[i] == 'weekly':

Additionally replace:

for in in plants_d:

with:

for i in plants_d:

because "in" is keyword.

To avoid searching n times value from dictionary you should use items() function. It creates list of pairs from dictionary. Then you can iterate over them:

def weeklies(plant_d):
    result = []
    for plant_name, description in plant_d.items():
        if description == "weekly":
            result.append(plant_name)
    return sorted(result)