2

I need to call a recursive function to print the contents of the nested dictionary like this on separate lines:

lunch : {"sandwich": 2, "chips": 1, "drink": 1}

dinner : {"ribs": 6, "mac_cheese": 1, "roll": 1, "pie": 1}

I tried the following code but it is just iterating over the keys of the nested dictionary

# recursive function for printing out meal plans 
def print_meals(meal_plan):
    for key, value in meal_plan.items():
        if type(value) is dict:
            print_meals(value)
        else:
            print(key, ":", value)

    # create an empty dictionary
    meal_plan = {}

    # create individual dictionaries for each meal
    lunch = {"sandwich": 2, "chips": 1, "drink": 1}
    dinner = {"ribs": 6, "mac_cheese": 1, "roll": 1, "pie": 1}

    #create a nested dictionary
    meal_plan["lunch"] = lunch 
    meal_plan["dinner"] = dinner 

    # call recursive function 'print_meals'
    print_meals(meal_plan)
5
  • 1
    Where is the nested dictionary in input? I could see , all are plain dictionary. Commented Oct 16, 2021 at 12:48
  • @JohnByro I am creating the nested dictionary under the comment for create a nested dictionary. It is being stored in the dictionary meal_plan Commented Oct 16, 2021 at 12:53
  • 1
    Is it guaranteed that there will only be one level of depth in the nested dictionary? Or could you have for instance meal_plan = {'monday': {'lunch': {...}, 'dinner': {...}}, 'tuesday': {...}} Commented Oct 16, 2021 at 12:55
  • I recommend using isinstance(value, dict) rather than type(value) is dict. For instance, if value is a subclass of dict, then isinstance(value, dict) will still return True, but type(value) is dict will return False. Commented Oct 16, 2021 at 14:55
  • If there aren't arbitrary levels of nesting you don't need recursion. Commented Oct 16, 2021 at 17:46

2 Answers 2

1

you can define your function like below:

>>> def print_meals(dct):
...    for k,v in dct.items():
...        print(f'{k} : {v}');print()

Output:

>>> meal_plan
{'lunch': {'sandwich': 2, 'chips': 1, 'drink': 1},
 'dinner': {'ribs': 6, 'mac_cheese': 1, 'roll': 1, 'pie': 1}}

>>> print_meals(meal_plan)
lunch : {'sandwich': 2, 'chips': 1, 'drink': 1}

dinner : {'ribs': 6, 'mac_cheese': 1, 'roll': 1, 'pie': 1}

Sign up to request clarification or add additional context in comments.

Comments

0

Here is an idea:

def print_meals(meal_plan, depth=0):
    if isinstance(meal_plan, dict):
        for k, v in meal_plan.items():
            print('  '*depth, k, ':')
            print_meals(v, depth+1)
    else:
        print('  '*depth, meal_plan)

print_meals('sandwich')
#  sandwich

print_meals({'sandwich': 1})
#  sandwich :
#    1

print_meals({'lunch': {'sandwich': 2, 'chips': 1, 'drink': 1}, 'dinner': {'ribs': 6, 'mac_cheese': 1, 'roll': 1, 'pie': 1}})
#  lunch :
#    sandwich :
#      2
#    chips :
#      1
#    drink :
#      1
#  dinner :
#    ribs :
#      6
#    mac_cheese :
#      1
#    roll :
#      1
#    pie :
#      1

print_meals({'monday': {'lunch': {'sandwich': 1, 'apple': 2}, 'dinner': {'soup': 1, 'yaourt': 1}}, 'tuesday': {'breakfast': 'pain au chocolat', 'lunch': {'salad': 2, 'lasagna': 1}, 'dinner': {'beans':3}}})
#  monday :
#    lunch :
#      sandwich :
#        1
#      apple :
#        2
#    dinner :
#      soup :
#        1
#      yaourt :
#        1
#  tuesday :
#    breakfast :
#      pain au chocolat
#    lunch :
#      salad :
#        2
#      lasagna :
#        1
#    dinner :
#      beans :
#        3

Alternatively, for fewer line breaks, but assumes the meal plan is a dict:

def print_meals(meal_plan, depth=0):
  for k,v in meal_plan.items():
    if isinstance(v, dict):
      print('  '*depth, k, ':')
      print_meals(v, depth+1)
    else:
      print('  '*depth, k, ':', v)

print_meals({'sandwich': 1})
#  sandwich : 1

print_meals({'lunch': {'sandwich': 2, 'chips': 1, 'drink': 1}, 'dinner': {'ribs': 6, 'mac_cheese': 1, 'roll': 1, 'pie': 1}})
#  lunch :
#    sandwich : 2
#    chips : 1
#    drink : 1
#  dinner :
#    ribs : 6
#    mac_cheese : 1
#    roll : 1
#    pie : 1

print_meals({'monday': {'lunch': {'sandwich': 1, 'apple': 2}, 'dinner': {'soup': 1, 'yaourt': 1}}, 'tuesday': {'breakfast': 'pain au chocolat', 'lunch': {'salad': 2, 'lasagna': 1}, 'dinner': {'beans':3}}})
#  monday :
#    lunch :
#      sandwich : 1
#      apple : 2
#    dinner :
#      soup : 1
#      yaourt : 1
#  tuesday :
#    breakfast : pain au chocolat
#    lunch :
#      salad : 2
#      lasagna : 1
#    dinner :
#      beans : 3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.