Python Forum
Two variables in loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Two variables in loop (/thread-28576.html)



Two variables in loop - Ferdis - Jul-24-2020

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



RE: Two variables in loop - buran - Jul-24-2020

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