Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Two variables in loop
#1
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
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Creating a loop with dynamic variables instead of hardcoded values FugaziRocks 3 1,492 Jul-27-2022, 08:50 PM
Last Post: rob101
  WHILE Loop - constant variables NOT working with user input boundaries C0D3R 4 1,484 Apr-05-2022, 06:18 AM
Last Post: C0D3R
  how to use 3 variables python loop evilcode1 2 1,674 Nov-12-2021, 11:43 AM
Last Post: jamesaarr
  Creating a variables inside FOR loop zazas321 5 4,105 Sep-16-2020, 04:42 PM
Last Post: Naheed
  Create, assign and print variables in loop steven_tr 10 4,354 May-28-2020, 04:26 PM
Last Post: ndc85430
  Two variables in for loop vipinv23 9 13,991 Aug-26-2019, 05:30 AM
Last Post: newbieAuggie2019
  Operations on indexed variables in loop Fibulavie 1 1,935 Aug-14-2019, 06:07 AM
Last Post: fishhook
  labelling variables of df with map() in loop theinzawoo 2 2,495 Mar-19-2019, 03:42 AM
Last Post: theinzawoo
  I need help with loop one function and creating variables don 3 2,813 Jan-24-2019, 07:31 AM
Last Post: buran
  I can't figure out how to create variables in a while loop MrCag 1 2,361 May-08-2018, 08:56 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020