这段代码完成了它应该做的事情。我的挂断是理解词典中的键是什么以及它的价值是什么。我是(〜仍然)确定它是--dict = {key:value} - 但是在运行下面的代码时,它似乎正好相反。有人可以放下心来休息并澄清我所缺少的东西。我不想在没有彻底了解的情况下继续前进。感谢。
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
输出:
orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
price: 2
stock: 0
117.0
None
答案 0 :(得分:1)
您的理解是正确的,它是{key:value},您的代码会支持它。
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.
这正是您应该期望它做的事情。你的困惑在哪里(即,它在哪里表现出与你描述的相反)?
答案 1 :(得分:1)
将字典想象成城市街道。键是地址,值是特定地址的值:
from pprint import pprint
first_street = {
100: 'some house',
101: 'some other house'
}
pprint(first_street)
地址不一定是数字,它们可以是任何不可变的数据类型,int,string,tuple等。
答案 2 :(得分:0)
你是对的 - dicts包含key: value
对(按此顺序)。也许你很困惑,那个键可以是任何不可变类型。
我建议您浏览一下有关该主题的文档:https://docs.python.org/2/library/stdtypes.html#dict