这段代码可以完成预期的工作。我的挂断电话是了解字典中的键是什么,值是什么。我(仍然是)确信它是-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
最佳答案
您的理解是正确的,它是{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.
这正是您应该期望的。您的困惑在哪里(即与您描述的相反)在哪里?
关于python - Python字典中的键/值混淆,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27663707/