Testing nested dictionaries for a user input and retrieving directly related information










0















I’m new to Python 3 and have been experimenting with Dictionaries but I’m having problems testing for a specific key and retrieving its related values from nested dictionaries.



I want a user defined input to be checked against nested dictionaries and if the user input is found I then want to collect the details for that item and add it to another dictionary.



E.g.



basketDict = 
shopDict = "Fruit": "Apple": "2", "Banana": "3",
"Vegetables": "Lettuce": "5", "Potato": "7"
userQuery = input("What food do you want to check for? ")


userQuery = "Apple"



Desired result:



basketDict = "Fruit": "Apple": "2"


I've attempted to use dictionary comprehension to form a new dictionary of only food items (Apple, Banana, Lettuce etc.) but keep running into issues when trying to collect the related category ("Fruit"/"Vegetable" and quantity information from the nested dictionaries.



Here's my (broken) code:



basketDict = 
shopDict = "Fruit": "Apple": "2", "Banana": "3",
"Vegetables": "Lettuce": "5", "Potato": "7"
shopCheck =

userQuery = input("What food do you want to check for? ")
for category, food in shopDict.items():
for each in food:
shopCheck.append(each)

if userQuery not in shopCheck:
print("That's not available.")
else:
print(userQuery + " added to basket. ")
basketDict[category] = [food]

print(basketDict)









share|improve this question




























    0















    I’m new to Python 3 and have been experimenting with Dictionaries but I’m having problems testing for a specific key and retrieving its related values from nested dictionaries.



    I want a user defined input to be checked against nested dictionaries and if the user input is found I then want to collect the details for that item and add it to another dictionary.



    E.g.



    basketDict = 
    shopDict = "Fruit": "Apple": "2", "Banana": "3",
    "Vegetables": "Lettuce": "5", "Potato": "7"
    userQuery = input("What food do you want to check for? ")


    userQuery = "Apple"



    Desired result:



    basketDict = "Fruit": "Apple": "2"


    I've attempted to use dictionary comprehension to form a new dictionary of only food items (Apple, Banana, Lettuce etc.) but keep running into issues when trying to collect the related category ("Fruit"/"Vegetable" and quantity information from the nested dictionaries.



    Here's my (broken) code:



    basketDict = 
    shopDict = "Fruit": "Apple": "2", "Banana": "3",
    "Vegetables": "Lettuce": "5", "Potato": "7"
    shopCheck =

    userQuery = input("What food do you want to check for? ")
    for category, food in shopDict.items():
    for each in food:
    shopCheck.append(each)

    if userQuery not in shopCheck:
    print("That's not available.")
    else:
    print(userQuery + " added to basket. ")
    basketDict[category] = [food]

    print(basketDict)









    share|improve this question


























      0












      0








      0








      I’m new to Python 3 and have been experimenting with Dictionaries but I’m having problems testing for a specific key and retrieving its related values from nested dictionaries.



      I want a user defined input to be checked against nested dictionaries and if the user input is found I then want to collect the details for that item and add it to another dictionary.



      E.g.



      basketDict = 
      shopDict = "Fruit": "Apple": "2", "Banana": "3",
      "Vegetables": "Lettuce": "5", "Potato": "7"
      userQuery = input("What food do you want to check for? ")


      userQuery = "Apple"



      Desired result:



      basketDict = "Fruit": "Apple": "2"


      I've attempted to use dictionary comprehension to form a new dictionary of only food items (Apple, Banana, Lettuce etc.) but keep running into issues when trying to collect the related category ("Fruit"/"Vegetable" and quantity information from the nested dictionaries.



      Here's my (broken) code:



      basketDict = 
      shopDict = "Fruit": "Apple": "2", "Banana": "3",
      "Vegetables": "Lettuce": "5", "Potato": "7"
      shopCheck =

      userQuery = input("What food do you want to check for? ")
      for category, food in shopDict.items():
      for each in food:
      shopCheck.append(each)

      if userQuery not in shopCheck:
      print("That's not available.")
      else:
      print(userQuery + " added to basket. ")
      basketDict[category] = [food]

      print(basketDict)









      share|improve this question
















      I’m new to Python 3 and have been experimenting with Dictionaries but I’m having problems testing for a specific key and retrieving its related values from nested dictionaries.



      I want a user defined input to be checked against nested dictionaries and if the user input is found I then want to collect the details for that item and add it to another dictionary.



      E.g.



      basketDict = 
      shopDict = "Fruit": "Apple": "2", "Banana": "3",
      "Vegetables": "Lettuce": "5", "Potato": "7"
      userQuery = input("What food do you want to check for? ")


      userQuery = "Apple"



      Desired result:



      basketDict = "Fruit": "Apple": "2"


      I've attempted to use dictionary comprehension to form a new dictionary of only food items (Apple, Banana, Lettuce etc.) but keep running into issues when trying to collect the related category ("Fruit"/"Vegetable" and quantity information from the nested dictionaries.



      Here's my (broken) code:



      basketDict = 
      shopDict = "Fruit": "Apple": "2", "Banana": "3",
      "Vegetables": "Lettuce": "5", "Potato": "7"
      shopCheck =

      userQuery = input("What food do you want to check for? ")
      for category, food in shopDict.items():
      for each in food:
      shopCheck.append(each)

      if userQuery not in shopCheck:
      print("That's not available.")
      else:
      print(userQuery + " added to basket. ")
      basketDict[category] = [food]

      print(basketDict)






      python python-3.x dictionary nested dictionary-comprehension






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 12 '18 at 15:31









      toti08

      1,74131523




      1,74131523










      asked Nov 12 '18 at 14:35









      MHSalehiMHSalehi

      32




      32






















          3 Answers
          3






          active

          oldest

          votes


















          0














          This code is enough for your requirements:



          for category, food in shopDict.items():
          if userQuery in food:
          basketDict[category] = userQuery: food[userQuery]


          But if you want to add new items to the basket, you should update it properly:



          for category, food in shopDict.items():
          if userQuery in food:
          basketDict.update(
          category: **basketDict.get(category, ),
          **userQuery: food[userQuery]
          )


          You want to merge the actual dictionary of the category (the basket's actual content) with the selected item's key-value.
          Generally in python3 if you have 2 dictionaries this is the way to merge them into one:



          d1 = "one": 1, "two": 2
          d2 = "three": 3
          merged = **d1, **d2 # 'one': 1, 'two': 2, 'three': 3


          Because ** is used to unpack the dictionary.



          Good way to understand it is if you have a function definition with some arguments, then you can call the function with a dictionary that has the argument names as keys. But you have to unpack it, otherwise you would pass the dictionary as the parameter, and not its values.



          d = "one": 1, "two": 2
          def example(one, two):
          pass


          example(d) would throw a TypeError, because it's missing the second positional argument, but example(**d) would work fine






          share|improve this answer

























          • This works wonderfully for my purpose. I am somewhat puzzled by the contents and structure of the basketDict.update() though - I'm not familiar with the '**' or structure of the contents within the (). Would you be able to provide an explanation or point me to resources where I can learn how it functions? Thanks for the solution.

            – MHSalehi
            Nov 12 '18 at 20:29












          • I made some changes to be more clear. Also, you don't have to use the method update, simply set the key's value: basketDict[category] = **basketDict.get(category, ), **userQuery: food[userQuery]

            – M.Adam
            Nov 13 '18 at 9:18



















          0














          Probably there's a simpler way to do this, but I just fixed your code.
          When I run your code, everything inside shopDict was going to basketDict. This is because you wasn't cleaning your shopCheck variable at each for iteration.
          And there was a second mistake when adding the elements to basketDict. You need to add only the food element that match the userQuery. Here's the full fixed code:



          basketDict = 
          shopDict = "Fruit": "Apple": "2", "Banana": "3",
          "Vegetables": "Lettuce": "5", "Potato": "7"

          userQuery = input("What food do you want to check for? ")
          for category, food in shopDict.items():
          shopCheck =
          for each in food:
          shopCheck.append(each)

          if userQuery not in shopCheck:
          print("That's not available.")
          else:
          print(userQuery + " added to basket. ")
          basketDict[category] = userQuery:food[userQuery]

          print(basketDict)





          share|improve this answer




















          • 1





            this too has indentation issues I guess

            – Manoj Kengudelu
            Nov 12 '18 at 14:55











          • @ManojKengudelu You was right. Fixed!

            – Hemerson Tacon
            Nov 12 '18 at 14:56












          • Thanks for the response. When I run this code and enter 'Apple', it erroneously produces, "That's not available." despite successfully adding it to the basketDict. Any ideas why?

            – MHSalehi
            Nov 12 '18 at 20:41











          • @MHSalehi Actualy if you analyse the code carefully you will see that is not an error. Since the shopDict has two pair of key-values (in this case category-food pairs), the outer for will be executed twice: one for the key "Fruit" and another for the key "Vegetables". That second iteration is generates that print because Apple indeed isn't present among the "Vegetable" values what is totaly right.

            – Hemerson Tacon
            Nov 13 '18 at 14:50


















          0














          I'd start by creating a dictionary containing all the items you can buy, whether they're fruit or vegetables. Then I'd simply check if the required item is on that dictionary:



          basketDict = 
          shopDict = "Fruit": "Apple": "2", "Banana": "3",
          "Vegetables": "Lettuce": "5", "Potato": "7"
          allVals =

          for k, subDict in shopDict.items():
          for k1, val in subDict.items():
          allVals[k1] = val


          userQuery = input("What food do you want to check for? ")
          if userQuery not in allVals.keys():
          print("That's not available.")
          else:
          print(userQuery + " added to basket. ")
          basketDict[userQuery] = allVals[userQuery]

          print(basketDict)





          share|improve this answer

























          • AttributeError: 'dict' object has no attribute 'iteritems'

            – Hemerson Tacon
            Nov 12 '18 at 14:52











          • Oops, sorry, I tested this with python2.7. I'll fix this!

            – toti08
            Nov 12 '18 at 15:04










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53264397%2ftesting-nested-dictionaries-for-a-user-input-and-retrieving-directly-related-inf%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          3 Answers
          3






          active

          oldest

          votes








          3 Answers
          3






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          This code is enough for your requirements:



          for category, food in shopDict.items():
          if userQuery in food:
          basketDict[category] = userQuery: food[userQuery]


          But if you want to add new items to the basket, you should update it properly:



          for category, food in shopDict.items():
          if userQuery in food:
          basketDict.update(
          category: **basketDict.get(category, ),
          **userQuery: food[userQuery]
          )


          You want to merge the actual dictionary of the category (the basket's actual content) with the selected item's key-value.
          Generally in python3 if you have 2 dictionaries this is the way to merge them into one:



          d1 = "one": 1, "two": 2
          d2 = "three": 3
          merged = **d1, **d2 # 'one': 1, 'two': 2, 'three': 3


          Because ** is used to unpack the dictionary.



          Good way to understand it is if you have a function definition with some arguments, then you can call the function with a dictionary that has the argument names as keys. But you have to unpack it, otherwise you would pass the dictionary as the parameter, and not its values.



          d = "one": 1, "two": 2
          def example(one, two):
          pass


          example(d) would throw a TypeError, because it's missing the second positional argument, but example(**d) would work fine






          share|improve this answer

























          • This works wonderfully for my purpose. I am somewhat puzzled by the contents and structure of the basketDict.update() though - I'm not familiar with the '**' or structure of the contents within the (). Would you be able to provide an explanation or point me to resources where I can learn how it functions? Thanks for the solution.

            – MHSalehi
            Nov 12 '18 at 20:29












          • I made some changes to be more clear. Also, you don't have to use the method update, simply set the key's value: basketDict[category] = **basketDict.get(category, ), **userQuery: food[userQuery]

            – M.Adam
            Nov 13 '18 at 9:18
















          0














          This code is enough for your requirements:



          for category, food in shopDict.items():
          if userQuery in food:
          basketDict[category] = userQuery: food[userQuery]


          But if you want to add new items to the basket, you should update it properly:



          for category, food in shopDict.items():
          if userQuery in food:
          basketDict.update(
          category: **basketDict.get(category, ),
          **userQuery: food[userQuery]
          )


          You want to merge the actual dictionary of the category (the basket's actual content) with the selected item's key-value.
          Generally in python3 if you have 2 dictionaries this is the way to merge them into one:



          d1 = "one": 1, "two": 2
          d2 = "three": 3
          merged = **d1, **d2 # 'one': 1, 'two': 2, 'three': 3


          Because ** is used to unpack the dictionary.



          Good way to understand it is if you have a function definition with some arguments, then you can call the function with a dictionary that has the argument names as keys. But you have to unpack it, otherwise you would pass the dictionary as the parameter, and not its values.



          d = "one": 1, "two": 2
          def example(one, two):
          pass


          example(d) would throw a TypeError, because it's missing the second positional argument, but example(**d) would work fine






          share|improve this answer

























          • This works wonderfully for my purpose. I am somewhat puzzled by the contents and structure of the basketDict.update() though - I'm not familiar with the '**' or structure of the contents within the (). Would you be able to provide an explanation or point me to resources where I can learn how it functions? Thanks for the solution.

            – MHSalehi
            Nov 12 '18 at 20:29












          • I made some changes to be more clear. Also, you don't have to use the method update, simply set the key's value: basketDict[category] = **basketDict.get(category, ), **userQuery: food[userQuery]

            – M.Adam
            Nov 13 '18 at 9:18














          0












          0








          0







          This code is enough for your requirements:



          for category, food in shopDict.items():
          if userQuery in food:
          basketDict[category] = userQuery: food[userQuery]


          But if you want to add new items to the basket, you should update it properly:



          for category, food in shopDict.items():
          if userQuery in food:
          basketDict.update(
          category: **basketDict.get(category, ),
          **userQuery: food[userQuery]
          )


          You want to merge the actual dictionary of the category (the basket's actual content) with the selected item's key-value.
          Generally in python3 if you have 2 dictionaries this is the way to merge them into one:



          d1 = "one": 1, "two": 2
          d2 = "three": 3
          merged = **d1, **d2 # 'one': 1, 'two': 2, 'three': 3


          Because ** is used to unpack the dictionary.



          Good way to understand it is if you have a function definition with some arguments, then you can call the function with a dictionary that has the argument names as keys. But you have to unpack it, otherwise you would pass the dictionary as the parameter, and not its values.



          d = "one": 1, "two": 2
          def example(one, two):
          pass


          example(d) would throw a TypeError, because it's missing the second positional argument, but example(**d) would work fine






          share|improve this answer















          This code is enough for your requirements:



          for category, food in shopDict.items():
          if userQuery in food:
          basketDict[category] = userQuery: food[userQuery]


          But if you want to add new items to the basket, you should update it properly:



          for category, food in shopDict.items():
          if userQuery in food:
          basketDict.update(
          category: **basketDict.get(category, ),
          **userQuery: food[userQuery]
          )


          You want to merge the actual dictionary of the category (the basket's actual content) with the selected item's key-value.
          Generally in python3 if you have 2 dictionaries this is the way to merge them into one:



          d1 = "one": 1, "two": 2
          d2 = "three": 3
          merged = **d1, **d2 # 'one': 1, 'two': 2, 'three': 3


          Because ** is used to unpack the dictionary.



          Good way to understand it is if you have a function definition with some arguments, then you can call the function with a dictionary that has the argument names as keys. But you have to unpack it, otherwise you would pass the dictionary as the parameter, and not its values.



          d = "one": 1, "two": 2
          def example(one, two):
          pass


          example(d) would throw a TypeError, because it's missing the second positional argument, but example(**d) would work fine







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 13 '18 at 9:20

























          answered Nov 12 '18 at 15:21









          M.AdamM.Adam

          8614




          8614












          • This works wonderfully for my purpose. I am somewhat puzzled by the contents and structure of the basketDict.update() though - I'm not familiar with the '**' or structure of the contents within the (). Would you be able to provide an explanation or point me to resources where I can learn how it functions? Thanks for the solution.

            – MHSalehi
            Nov 12 '18 at 20:29












          • I made some changes to be more clear. Also, you don't have to use the method update, simply set the key's value: basketDict[category] = **basketDict.get(category, ), **userQuery: food[userQuery]

            – M.Adam
            Nov 13 '18 at 9:18


















          • This works wonderfully for my purpose. I am somewhat puzzled by the contents and structure of the basketDict.update() though - I'm not familiar with the '**' or structure of the contents within the (). Would you be able to provide an explanation or point me to resources where I can learn how it functions? Thanks for the solution.

            – MHSalehi
            Nov 12 '18 at 20:29












          • I made some changes to be more clear. Also, you don't have to use the method update, simply set the key's value: basketDict[category] = **basketDict.get(category, ), **userQuery: food[userQuery]

            – M.Adam
            Nov 13 '18 at 9:18

















          This works wonderfully for my purpose. I am somewhat puzzled by the contents and structure of the basketDict.update() though - I'm not familiar with the '**' or structure of the contents within the (). Would you be able to provide an explanation or point me to resources where I can learn how it functions? Thanks for the solution.

          – MHSalehi
          Nov 12 '18 at 20:29






          This works wonderfully for my purpose. I am somewhat puzzled by the contents and structure of the basketDict.update() though - I'm not familiar with the '**' or structure of the contents within the (). Would you be able to provide an explanation or point me to resources where I can learn how it functions? Thanks for the solution.

          – MHSalehi
          Nov 12 '18 at 20:29














          I made some changes to be more clear. Also, you don't have to use the method update, simply set the key's value: basketDict[category] = **basketDict.get(category, ), **userQuery: food[userQuery]

          – M.Adam
          Nov 13 '18 at 9:18






          I made some changes to be more clear. Also, you don't have to use the method update, simply set the key's value: basketDict[category] = **basketDict.get(category, ), **userQuery: food[userQuery]

          – M.Adam
          Nov 13 '18 at 9:18














          0














          Probably there's a simpler way to do this, but I just fixed your code.
          When I run your code, everything inside shopDict was going to basketDict. This is because you wasn't cleaning your shopCheck variable at each for iteration.
          And there was a second mistake when adding the elements to basketDict. You need to add only the food element that match the userQuery. Here's the full fixed code:



          basketDict = 
          shopDict = "Fruit": "Apple": "2", "Banana": "3",
          "Vegetables": "Lettuce": "5", "Potato": "7"

          userQuery = input("What food do you want to check for? ")
          for category, food in shopDict.items():
          shopCheck =
          for each in food:
          shopCheck.append(each)

          if userQuery not in shopCheck:
          print("That's not available.")
          else:
          print(userQuery + " added to basket. ")
          basketDict[category] = userQuery:food[userQuery]

          print(basketDict)





          share|improve this answer




















          • 1





            this too has indentation issues I guess

            – Manoj Kengudelu
            Nov 12 '18 at 14:55











          • @ManojKengudelu You was right. Fixed!

            – Hemerson Tacon
            Nov 12 '18 at 14:56












          • Thanks for the response. When I run this code and enter 'Apple', it erroneously produces, "That's not available." despite successfully adding it to the basketDict. Any ideas why?

            – MHSalehi
            Nov 12 '18 at 20:41











          • @MHSalehi Actualy if you analyse the code carefully you will see that is not an error. Since the shopDict has two pair of key-values (in this case category-food pairs), the outer for will be executed twice: one for the key "Fruit" and another for the key "Vegetables". That second iteration is generates that print because Apple indeed isn't present among the "Vegetable" values what is totaly right.

            – Hemerson Tacon
            Nov 13 '18 at 14:50















          0














          Probably there's a simpler way to do this, but I just fixed your code.
          When I run your code, everything inside shopDict was going to basketDict. This is because you wasn't cleaning your shopCheck variable at each for iteration.
          And there was a second mistake when adding the elements to basketDict. You need to add only the food element that match the userQuery. Here's the full fixed code:



          basketDict = 
          shopDict = "Fruit": "Apple": "2", "Banana": "3",
          "Vegetables": "Lettuce": "5", "Potato": "7"

          userQuery = input("What food do you want to check for? ")
          for category, food in shopDict.items():
          shopCheck =
          for each in food:
          shopCheck.append(each)

          if userQuery not in shopCheck:
          print("That's not available.")
          else:
          print(userQuery + " added to basket. ")
          basketDict[category] = userQuery:food[userQuery]

          print(basketDict)





          share|improve this answer




















          • 1





            this too has indentation issues I guess

            – Manoj Kengudelu
            Nov 12 '18 at 14:55











          • @ManojKengudelu You was right. Fixed!

            – Hemerson Tacon
            Nov 12 '18 at 14:56












          • Thanks for the response. When I run this code and enter 'Apple', it erroneously produces, "That's not available." despite successfully adding it to the basketDict. Any ideas why?

            – MHSalehi
            Nov 12 '18 at 20:41











          • @MHSalehi Actualy if you analyse the code carefully you will see that is not an error. Since the shopDict has two pair of key-values (in this case category-food pairs), the outer for will be executed twice: one for the key "Fruit" and another for the key "Vegetables". That second iteration is generates that print because Apple indeed isn't present among the "Vegetable" values what is totaly right.

            – Hemerson Tacon
            Nov 13 '18 at 14:50













          0












          0








          0







          Probably there's a simpler way to do this, but I just fixed your code.
          When I run your code, everything inside shopDict was going to basketDict. This is because you wasn't cleaning your shopCheck variable at each for iteration.
          And there was a second mistake when adding the elements to basketDict. You need to add only the food element that match the userQuery. Here's the full fixed code:



          basketDict = 
          shopDict = "Fruit": "Apple": "2", "Banana": "3",
          "Vegetables": "Lettuce": "5", "Potato": "7"

          userQuery = input("What food do you want to check for? ")
          for category, food in shopDict.items():
          shopCheck =
          for each in food:
          shopCheck.append(each)

          if userQuery not in shopCheck:
          print("That's not available.")
          else:
          print(userQuery + " added to basket. ")
          basketDict[category] = userQuery:food[userQuery]

          print(basketDict)





          share|improve this answer















          Probably there's a simpler way to do this, but I just fixed your code.
          When I run your code, everything inside shopDict was going to basketDict. This is because you wasn't cleaning your shopCheck variable at each for iteration.
          And there was a second mistake when adding the elements to basketDict. You need to add only the food element that match the userQuery. Here's the full fixed code:



          basketDict = 
          shopDict = "Fruit": "Apple": "2", "Banana": "3",
          "Vegetables": "Lettuce": "5", "Potato": "7"

          userQuery = input("What food do you want to check for? ")
          for category, food in shopDict.items():
          shopCheck =
          for each in food:
          shopCheck.append(each)

          if userQuery not in shopCheck:
          print("That's not available.")
          else:
          print(userQuery + " added to basket. ")
          basketDict[category] = userQuery:food[userQuery]

          print(basketDict)






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 12 '18 at 15:01

























          answered Nov 12 '18 at 14:51









          Hemerson TaconHemerson Tacon

          9371315




          9371315







          • 1





            this too has indentation issues I guess

            – Manoj Kengudelu
            Nov 12 '18 at 14:55











          • @ManojKengudelu You was right. Fixed!

            – Hemerson Tacon
            Nov 12 '18 at 14:56












          • Thanks for the response. When I run this code and enter 'Apple', it erroneously produces, "That's not available." despite successfully adding it to the basketDict. Any ideas why?

            – MHSalehi
            Nov 12 '18 at 20:41











          • @MHSalehi Actualy if you analyse the code carefully you will see that is not an error. Since the shopDict has two pair of key-values (in this case category-food pairs), the outer for will be executed twice: one for the key "Fruit" and another for the key "Vegetables". That second iteration is generates that print because Apple indeed isn't present among the "Vegetable" values what is totaly right.

            – Hemerson Tacon
            Nov 13 '18 at 14:50












          • 1





            this too has indentation issues I guess

            – Manoj Kengudelu
            Nov 12 '18 at 14:55











          • @ManojKengudelu You was right. Fixed!

            – Hemerson Tacon
            Nov 12 '18 at 14:56












          • Thanks for the response. When I run this code and enter 'Apple', it erroneously produces, "That's not available." despite successfully adding it to the basketDict. Any ideas why?

            – MHSalehi
            Nov 12 '18 at 20:41











          • @MHSalehi Actualy if you analyse the code carefully you will see that is not an error. Since the shopDict has two pair of key-values (in this case category-food pairs), the outer for will be executed twice: one for the key "Fruit" and another for the key "Vegetables". That second iteration is generates that print because Apple indeed isn't present among the "Vegetable" values what is totaly right.

            – Hemerson Tacon
            Nov 13 '18 at 14:50







          1




          1





          this too has indentation issues I guess

          – Manoj Kengudelu
          Nov 12 '18 at 14:55





          this too has indentation issues I guess

          – Manoj Kengudelu
          Nov 12 '18 at 14:55













          @ManojKengudelu You was right. Fixed!

          – Hemerson Tacon
          Nov 12 '18 at 14:56






          @ManojKengudelu You was right. Fixed!

          – Hemerson Tacon
          Nov 12 '18 at 14:56














          Thanks for the response. When I run this code and enter 'Apple', it erroneously produces, "That's not available." despite successfully adding it to the basketDict. Any ideas why?

          – MHSalehi
          Nov 12 '18 at 20:41





          Thanks for the response. When I run this code and enter 'Apple', it erroneously produces, "That's not available." despite successfully adding it to the basketDict. Any ideas why?

          – MHSalehi
          Nov 12 '18 at 20:41













          @MHSalehi Actualy if you analyse the code carefully you will see that is not an error. Since the shopDict has two pair of key-values (in this case category-food pairs), the outer for will be executed twice: one for the key "Fruit" and another for the key "Vegetables". That second iteration is generates that print because Apple indeed isn't present among the "Vegetable" values what is totaly right.

          – Hemerson Tacon
          Nov 13 '18 at 14:50





          @MHSalehi Actualy if you analyse the code carefully you will see that is not an error. Since the shopDict has two pair of key-values (in this case category-food pairs), the outer for will be executed twice: one for the key "Fruit" and another for the key "Vegetables". That second iteration is generates that print because Apple indeed isn't present among the "Vegetable" values what is totaly right.

          – Hemerson Tacon
          Nov 13 '18 at 14:50











          0














          I'd start by creating a dictionary containing all the items you can buy, whether they're fruit or vegetables. Then I'd simply check if the required item is on that dictionary:



          basketDict = 
          shopDict = "Fruit": "Apple": "2", "Banana": "3",
          "Vegetables": "Lettuce": "5", "Potato": "7"
          allVals =

          for k, subDict in shopDict.items():
          for k1, val in subDict.items():
          allVals[k1] = val


          userQuery = input("What food do you want to check for? ")
          if userQuery not in allVals.keys():
          print("That's not available.")
          else:
          print(userQuery + " added to basket. ")
          basketDict[userQuery] = allVals[userQuery]

          print(basketDict)





          share|improve this answer

























          • AttributeError: 'dict' object has no attribute 'iteritems'

            – Hemerson Tacon
            Nov 12 '18 at 14:52











          • Oops, sorry, I tested this with python2.7. I'll fix this!

            – toti08
            Nov 12 '18 at 15:04















          0














          I'd start by creating a dictionary containing all the items you can buy, whether they're fruit or vegetables. Then I'd simply check if the required item is on that dictionary:



          basketDict = 
          shopDict = "Fruit": "Apple": "2", "Banana": "3",
          "Vegetables": "Lettuce": "5", "Potato": "7"
          allVals =

          for k, subDict in shopDict.items():
          for k1, val in subDict.items():
          allVals[k1] = val


          userQuery = input("What food do you want to check for? ")
          if userQuery not in allVals.keys():
          print("That's not available.")
          else:
          print(userQuery + " added to basket. ")
          basketDict[userQuery] = allVals[userQuery]

          print(basketDict)





          share|improve this answer

























          • AttributeError: 'dict' object has no attribute 'iteritems'

            – Hemerson Tacon
            Nov 12 '18 at 14:52











          • Oops, sorry, I tested this with python2.7. I'll fix this!

            – toti08
            Nov 12 '18 at 15:04













          0












          0








          0







          I'd start by creating a dictionary containing all the items you can buy, whether they're fruit or vegetables. Then I'd simply check if the required item is on that dictionary:



          basketDict = 
          shopDict = "Fruit": "Apple": "2", "Banana": "3",
          "Vegetables": "Lettuce": "5", "Potato": "7"
          allVals =

          for k, subDict in shopDict.items():
          for k1, val in subDict.items():
          allVals[k1] = val


          userQuery = input("What food do you want to check for? ")
          if userQuery not in allVals.keys():
          print("That's not available.")
          else:
          print(userQuery + " added to basket. ")
          basketDict[userQuery] = allVals[userQuery]

          print(basketDict)





          share|improve this answer















          I'd start by creating a dictionary containing all the items you can buy, whether they're fruit or vegetables. Then I'd simply check if the required item is on that dictionary:



          basketDict = 
          shopDict = "Fruit": "Apple": "2", "Banana": "3",
          "Vegetables": "Lettuce": "5", "Potato": "7"
          allVals =

          for k, subDict in shopDict.items():
          for k1, val in subDict.items():
          allVals[k1] = val


          userQuery = input("What food do you want to check for? ")
          if userQuery not in allVals.keys():
          print("That's not available.")
          else:
          print(userQuery + " added to basket. ")
          basketDict[userQuery] = allVals[userQuery]

          print(basketDict)






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 12 '18 at 15:04

























          answered Nov 12 '18 at 14:49









          toti08toti08

          1,74131523




          1,74131523












          • AttributeError: 'dict' object has no attribute 'iteritems'

            – Hemerson Tacon
            Nov 12 '18 at 14:52











          • Oops, sorry, I tested this with python2.7. I'll fix this!

            – toti08
            Nov 12 '18 at 15:04

















          • AttributeError: 'dict' object has no attribute 'iteritems'

            – Hemerson Tacon
            Nov 12 '18 at 14:52











          • Oops, sorry, I tested this with python2.7. I'll fix this!

            – toti08
            Nov 12 '18 at 15:04
















          AttributeError: 'dict' object has no attribute 'iteritems'

          – Hemerson Tacon
          Nov 12 '18 at 14:52





          AttributeError: 'dict' object has no attribute 'iteritems'

          – Hemerson Tacon
          Nov 12 '18 at 14:52













          Oops, sorry, I tested this with python2.7. I'll fix this!

          – toti08
          Nov 12 '18 at 15:04





          Oops, sorry, I tested this with python2.7. I'll fix this!

          – toti08
          Nov 12 '18 at 15:04

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53264397%2ftesting-nested-dictionaries-for-a-user-input-and-retrieving-directly-related-inf%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          How to read a connectionString WITH PROVIDER in .NET Core?

          Node.js Script on GitHub Pages or Amazon S3

          Museum of Modern and Contemporary Art of Trento and Rovereto