不打印&&不给错误,为什么?
#!/usr/bin/python
prices = {"banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3}
stock = {"banana" : 6, "apple" : 0, "orange" : 32, "pear" : 15}
for item in set(prices) & set(stock):
if prices[item] == stock[item]:
print item
print "price: " + str(prices[item])
print "stock: " + str(stock[item])
答案 0 :(得分:2)
您正在比较每个共享密钥的值,但这些值都不相等:
>>> for item in set(prices) & set(stock):
... print '{:6}: {:3} == {:2} = {}'.format(item, prices[item], stock[item], prices[item] == stock[item])
...
orange: 1.5 == 32 = False
pear : 3 == 15 = False
banana: 4 == 6 = False
apple : 2 == 0 = False
条件prices[item] == stock[item]
永远不会为真。
答案 1 :(得分:1)
因为在这:
set(prices) & set(stock)
您正在进行交叉,您将获得prices
和stock
之间的所有常用项目(无需再次检查),因此您可能只想打印它:
for item in set(prices) & set(stock):
print item
print "price: " + str(prices[item])
print "stock: " + str(stock[item])
<强>输出:强>
orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
price: 2
stock: 0
PS:我假设这是OP所期望的。