Max Phillips
Max Phillips

Reputation: 7489

Key/Value Confusion in Python Dictionaries

This code does what it's supposed to do. My hang up is understanding what the key in a dictionary is and what the value is. I was (~still am) sure it was -- dict = {key : value} -- But upon running the code below it appears to be the opposite. Can someone put my mind to rest and clarify what I'm missing. I don't want to move on without thoroughly understanding it. Thanks.

prices = {
"banana" : 4,
"apple"  : 2,
"orange" : 1.5,
"pear"   : 3,
}
stock = {
"banana" : 6,
"apple"  : 0,
"orange" : 32,
"pear"   : 15,
}

total = 0
for key in prices:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]
    total = total + prices[key]*stock[key]
print

print total

output:

orange
price: 1.5
stock: 32

pear
price: 3
stock: 15

banana
price: 4
stock: 6

apple
price: 2
stock: 0

117.0
None

Upvotes: 1

Views: 307

Answers (3)

baited
baited

Reputation: 326

Think of a dictionary as a city street. The keys are the address, a value is what is at a particular address:

from pprint import pprint
first_street = {
    100: 'some house',
    101: 'some other house'
}
pprint(first_street)

The addresses do not have to be numbers, they can be any immutable data type, int, string, tuple, etc.

Upvotes: 1

tomasbedrich
tomasbedrich

Reputation: 1370

You are right - dicts contains pairs of key: value (in that order). Maybe you are confused, that key can be any immutable type. I would recommend you to walk through a documentation on that topic: https://docs.python.org/2/library/stdtypes.html#dict

Upvotes: 0

sberry
sberry

Reputation: 132018

Your understanding is correct, it is {key: value} and your code backs that up.

for key in prices:  # iterates through the keys of prices ["orange", "apple", "pear", "banana"] (though no ordering is guaranteed)
    print key # prints "orange"

    print "price: %s" % prices[key] # prints prices["orange"] (1.5) 
    # which means it prints the value of the prices dict, orange key.

    print "stock: %s" % stock[key] # prints stock["orange"] (32) 
    #which means it prints the value of the stock dict, orange key.

This is doing exactly what you should expect it to do. Where is your confusion (ie. Where does it seem to behave the opposite of what you described)?

Upvotes: 1

Related Questions