Reputation: 962
I am learning programming in Python. My task is to create two dictionaries with these values:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15
}
I am tasked to print out things about the dictionary in this format: I was supposed to use a FOR loop to access the data.
apple
price: 2
stock: 0
The instructions said that since the two dictionaries have the same "keys" that I could access both of them at the same time. However I don't know what this means. Learning Python so far has been a breeze, but this has me stumped.
Upvotes: 0
Views: 122
Reputation: 13321
A dictionary is a list of "key: value" pairs. When you want to get the value from a dictionary you specify the key which points to that value. Since both dictionaries you mentioned have the same keys (e.g., apple, banana), you can use the same key to get values out of both of them.
In order to get all of the keys in a dictionary, you can use the "keys" function. So the code you want is:
for key in prices.keys():
print(key)
print("prices: %s" % prices[key])
print("stock: %s" % stock[key])
Upvotes: 0
Reputation: 1121406
Both dictionaries have a 'banana'
key, both have a 'apple'
key, etc. Presumably that means you can loop over the keys of one and rely on the same key being present in the other:
for key in stock:
print key, stock[key], prices[key]
The above code will print the keys in stock
, adding the value from that dictionary and also looking up the value in prices
. If prices
does not have the same keys, the code would fail with a KeyError
.
I'll leave the actual output up to you, but now your problem is reduced to calculating the stock value.
Upvotes: 5