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











up vote
0
down vote

favorite












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




























    up vote
    0
    down vote

    favorite












    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


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      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 at 15:31









      toti08

      1,74721523




      1,74721523










      asked Nov 12 at 14:35









      MHSalehi

      32




      32
























          3 Answers
          3






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          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 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 at 9:18




















          up vote
          0
          down vote













          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 at 14:55










          • @ManojKengudelu You was right. Fixed!
            – Hemerson Tacon
            Nov 12 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 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 at 14:50


















          up vote
          0
          down vote













          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 at 14:52










          • Oops, sorry, I tested this with python2.7. I'll fix this!
            – toti08
            Nov 12 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',
          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








          up vote
          0
          down vote



          accepted










          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 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 at 9:18

















          up vote
          0
          down vote



          accepted










          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 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 at 9:18















          up vote
          0
          down vote



          accepted







          up vote
          0
          down vote



          accepted






          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 at 9:20

























          answered Nov 12 at 15:21









          M.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 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 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 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 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 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 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 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 at 9:18














          up vote
          0
          down vote













          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 at 14:55










          • @ManojKengudelu You was right. Fixed!
            – Hemerson Tacon
            Nov 12 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 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 at 14:50















          up vote
          0
          down vote













          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 at 14:55










          • @ManojKengudelu You was right. Fixed!
            – Hemerson Tacon
            Nov 12 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 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 at 14:50













          up vote
          0
          down vote










          up vote
          0
          down vote









          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 at 15:01

























          answered Nov 12 at 14:51









          Hemerson Tacon

          887315




          887315








          • 1




            this too has indentation issues I guess
            – Manoj Kengudelu
            Nov 12 at 14:55










          • @ManojKengudelu You was right. Fixed!
            – Hemerson Tacon
            Nov 12 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 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 at 14:50














          • 1




            this too has indentation issues I guess
            – Manoj Kengudelu
            Nov 12 at 14:55










          • @ManojKengudelu You was right. Fixed!
            – Hemerson Tacon
            Nov 12 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 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 at 14:50








          1




          1




          this too has indentation issues I guess
          – Manoj Kengudelu
          Nov 12 at 14:55




          this too has indentation issues I guess
          – Manoj Kengudelu
          Nov 12 at 14:55












          @ManojKengudelu You was right. Fixed!
          – Hemerson Tacon
          Nov 12 at 14:56






          @ManojKengudelu You was right. Fixed!
          – Hemerson Tacon
          Nov 12 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 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 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 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 at 14:50










          up vote
          0
          down vote













          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 at 14:52










          • Oops, sorry, I tested this with python2.7. I'll fix this!
            – toti08
            Nov 12 at 15:04















          up vote
          0
          down vote













          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 at 14:52










          • Oops, sorry, I tested this with python2.7. I'll fix this!
            – toti08
            Nov 12 at 15:04













          up vote
          0
          down vote










          up vote
          0
          down vote









          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 at 15:04

























          answered Nov 12 at 14:49









          toti08

          1,74721523




          1,74721523












          • AttributeError: 'dict' object has no attribute 'iteritems'
            – Hemerson Tacon
            Nov 12 at 14:52










          • Oops, sorry, I tested this with python2.7. I'll fix this!
            – toti08
            Nov 12 at 15:04


















          • AttributeError: 'dict' object has no attribute 'iteritems'
            – Hemerson Tacon
            Nov 12 at 14:52










          • Oops, sorry, I tested this with python2.7. I'll fix this!
            – toti08
            Nov 12 at 15:04
















          AttributeError: 'dict' object has no attribute 'iteritems'
          – Hemerson Tacon
          Nov 12 at 14:52




          AttributeError: 'dict' object has no attribute 'iteritems'
          – Hemerson Tacon
          Nov 12 at 14:52












          Oops, sorry, I tested this with python2.7. I'll fix this!
          – toti08
          Nov 12 at 15:04




          Oops, sorry, I tested this with python2.7. I'll fix this!
          – toti08
          Nov 12 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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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







          Popular posts from this blog

          鏡平學校

          ꓛꓣだゔៀៅຸ໢ທຮ໕໒ ,ໂ'໥໓າ໼ឨឲ៵៭ៈゎゔit''䖳𥁄卿' ☨₤₨こゎもょの;ꜹꟚꞖꞵꟅꞛေၦေɯ,ɨɡ𛃵𛁹ޝ޳ޠ޾,ޤޒޯ޾𫝒𫠁သ𛅤チョ'サノބޘދ𛁐ᶿᶇᶀᶋᶠ㨑㽹⻮ꧬ꧹؍۩وَؠ㇕㇃㇪ ㇦㇋㇋ṜẰᵡᴠ 軌ᵕ搜۳ٰޗޮ޷ސޯ𫖾𫅀ल, ꙭ꙰ꚅꙁꚊꞻꝔ꟠Ꝭㄤﺟޱސꧨꧼ꧴ꧯꧽ꧲ꧯ'⽹⽭⾁⿞⼳⽋២៩ញណើꩯꩤ꩸ꩮᶻᶺᶧᶂ𫳲𫪭𬸄𫵰𬖩𬫣𬊉ၲ𛅬㕦䬺𫝌𫝼,,𫟖𫞽ហៅ஫㆔ాఆఅꙒꚞꙍ,Ꙟ꙱エ ,ポテ,フࢰࢯ𫟠𫞶 𫝤𫟠ﺕﹱﻜﻣ𪵕𪭸𪻆𪾩𫔷ġ,ŧآꞪ꟥,ꞔꝻ♚☹⛵𛀌ꬷꭞȄƁƪƬșƦǙǗdžƝǯǧⱦⱰꓕꓢႋ神 ဴ၀க௭எ௫ឫោ ' េㇷㇴㇼ神ㇸㇲㇽㇴㇼㇻㇸ'ㇸㇿㇸㇹㇰㆣꓚꓤ₡₧ ㄨㄟ㄂ㄖㄎ໗ツڒذ₶।ऩछएोञयूटक़कयँृी,冬'𛅢𛅥ㇱㇵㇶ𥄥𦒽𠣧𠊓𧢖𥞘𩔋цѰㄠſtʯʭɿʆʗʍʩɷɛ,əʏダヵㄐㄘR{gỚṖḺờṠṫảḙḭᴮᵏᴘᵀᵷᵕᴜᴏᵾq﮲ﲿﴽﭙ軌ﰬﶚﶧ﫲Ҝжюїкӈㇴffצּ﬘﭅﬈軌'ffistfflſtffतभफɳɰʊɲʎ𛁱𛁖𛁮𛀉 𛂯𛀞నఋŀŲ 𫟲𫠖𫞺ຆຆ ໹້໕໗ๆทԊꧢꧠ꧰ꓱ⿝⼑ŎḬẃẖỐẅ ,ờỰỈỗﮊDžȩꭏꭎꬻ꭮ꬿꭖꭥꭅ㇭神 ⾈ꓵꓑ⺄㄄ㄪㄙㄅㄇstA۵䞽ॶ𫞑𫝄㇉㇇゜軌𩜛𩳠Jﻺ‚Üမ႕ႌႊၐၸဓၞၞၡ៸wyvtᶎᶪᶹစဎ꣡꣰꣢꣤ٗ؋لㇳㇾㇻㇱ㆐㆔,,㆟Ⱶヤマފ޼ޝަݿݞݠݷݐ',ݘ,ݪݙݵ𬝉𬜁𫝨𫞘くせぉて¼óû×ó£…𛅑הㄙくԗԀ5606神45,神796'𪤻𫞧ꓐ㄁ㄘɥɺꓵꓲ3''7034׉ⱦⱠˆ“𫝋ȍ,ꩲ軌꩷ꩶꩧꩫఞ۔فڱێظペサ神ナᴦᵑ47 9238їﻂ䐊䔉㠸﬎ffiﬣ,לּᴷᴦᵛᵽ,ᴨᵤ ᵸᵥᴗᵈꚏꚉꚟ⻆rtǟƴ𬎎

          Guess what letter conforming each word