1

Trying to make a function that returns a list of values from the dictionary. If the plants are watered weekly, it would be appended into the list then later returned sorted. However, my code iterates each letter of 'weekly' instead of the whole string and I have no idea how to access the watering frequency of the dictionary items. Any explanations would be appreciated.

def weekly(plants_d):
    d = []
    for plant in plants_d:
        for plan in plants_d[plant]:
            if plan == "weekly":
                d.append[plan]
                    return sort(d)
weekly({'fern':'weekly', 'shamrock':'weekly', 'carnation':'weekly'})
# Should return like this: ['carnation','fern','shamrock'] 
Hal Lawrence
  • 111
  • 1
  • 8
  • `plants_d[plant]` is a string like `'weekly'`, so `for plan in plants_d[plant]` will loop over the individual characters. – Barmar Nov 03 '16 at 19:36
  • Do you really have `return sort(d)` indented like that? It should be outside all the loops. – Barmar Nov 03 '16 at 19:42

3 Answers3

2

Amending the previous answer so that only values with "weekly" are used:

>>> my_dict = {'fern':'weekly', 'shamrock':'weekly', 'carnation':'weekly', 'daffodil': 'monthly'}
>>> sorted(k for k, v in my_dict.items() if v == 'weekly')
['carnation', 'fern', 'shamrock']
brianpck
  • 8,084
  • 1
  • 22
  • 33
1

This line:

for plan in plants_d[plant]:

is wrong. Since plants_d[plant] is a string like "weekly", this is like

for plan in "weekly":

which will iterate over the letters in the string. Then when you do if plan == "weekly": it will never match, because plan is just a single letter like "w".

You can simply use:

if plants_d[plan] == "weekly":

Or you can change the first loop to:

for plan_name, plan_frequency in plants_d.items():
    if plan_frequency == "weekly":
        d.append[plan_name]

See Iterating over dictionaries using 'for' loops

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Simplified way to achieve this is using dict.keys() which return the list of all the keys in dict. In order to sort the list, you may use sorted() as:

>>> my_dict = {'fern':'weekly', 'shamrock':'weekly', 'carnation':'weekly'}
>>> sorted(my_dict.keys())
['carnation', 'fern', 'shamrock']

Edit: If some the plans are monthly, firstly filter the monthly plans using filter or dict comprehension. Your code should be like:

>>> my_dict = {'fern':'weekly', 'shamrock':'weekly', 'carnation':'weekly', 
               'something': 'monthly'}
# using filter() as @brianpck has already mentioned 'dict comprehension' approach
# It is better to use brian's approach
>>> filtered_dict = dict(filter(lambda x: x[1] == 'weekly', my_dict.items())) 
>>> sorted(filtered_dict.keys())
['carnation', 'fern', 'shamrock']
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126