Say I have an empty dictionary that a user adds an arbitrary number of items into. After the user adds items to the dictionary, I want to then loop through that dictionary and be able to pull values out of it. What is the best way to access the items in the dictionary since I don't know the name of the key?
For example say I have the following:
# my shopping cart that starts off empty
shopping_cart = {}
# user enters how many items they will have in the cart total
total_items = input("How many items will you add to your cart? ")
# User adds both the value and the key of each item to add
for i in total_items:
name = input("Enter name of item to add: ")
location = input("Is the item in front, middle, or back of cart? ")
shopping_cart[name] = location
At this point I have a shopping_cart
dictionary, but I don't have a way to know what the KEYs or VALUEs are.
..... Now say there is some large string of thousands of characters in random order called random_string
. It looks like "axdfebzsdcdslapplefjdkslazpair....." Notice how the string is random, but periodically there are names of items like "apple" and "pair".
What I want to do is loop my shopping_cart
dictionary and find the next index position within my random_string
where the item in my shopping_cart
appears.
For example - let's say the user adds 3 items to the shopping cart. The items are "donkey", "apple", "pair".
What I want to do is read through the random_string
in order, and return the dictionary value that appears next in the string. I.E. in this case, "apple" is the next item in the random string, so it should be returned so I can lookup the value of "apple" in the dictionary and get the location of the item.
I have working code to do everything that is necessary EXCEPT for knowing how to pull the Keys out of the dictionary. I've copied a line below that essentially shows what I'm trying to accomplish. The problem is I don't know what DICT_KEY is, because it was added by the user.
index = random_string.find([DICT_KEY], index)
........ Not to confuse things, but I'm considering making an empty list that mirrors the dictionary values. In other words, when the user adds the item "apple" to the dictionary, I could add it to the dictionary and to the list. That way I can lookup the item in the dictionary by using it's index position in the list. seems like a bad way to handle this though, so happy to get any advice you can offer...
As you can see, I'm new at this!