Python Forum

Full Version: Two variables in loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, can someone help me understand how 'for dish, ingredients in food.items()' works?


def all_recipes_with(food): 
   result_dict={}
   for dish, ingredients in food.items(): 
      for ingredient in ingredients: 
         result_dict[ingredient] = result_dict.get(ingredients, [])
         result_dict[ingredient].append(dish) 
   return result_dict
food is expected to be mapping - e.g. dict with key and value pairs.
dict.items() will yield tuples (key, value) and in each iteration the tuple is unpacked into dish and ingredients names, i.e. dish will be the key and ingredients will be the value.

you can use http://www.pythontutor.com/visualize.html#mode=edit to visualise code execution step by step