繁体   English   中英

循环字典并打印值?

[英]Looping a dictionary and printing the values?

我在这里再问一次'因为我不知道怎么做...我有这个代码:

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

for e in prices and stock:
    print e
    print "price: " + str(e)
    print "stock: " + str(e)

并在

print "price: " + str(e)
print "stock: " + str(e) 

我想循环并打印价值,例如价格中的“1.5”和库存中的“32”,但是它打印键“橙色”并且我不知道如何循环和打印所有字典的值,可以你能帮帮我吗?

您只需要遍历其中一个字典,并使用映射访问来打印值:

for e in prices:
    print e
    print "price:", prices[e]
    print "stock:", stock[e]

但是,如果stock字典中没有prices中的键,则上述情况会引发KeyError

要确保两个字典中存在键,您可以使用字典视图来获取两个字典键集之间的集合交集:

for e in prices.viewkeys() & stock:
    print e
    print "price:", prices[e]
    print "stock:", stock[e]

这将循环两个字典中存在的那些键。

假设pricesstock之间的密钥总是相同的,您可以简单地这样做:

for key in prices:
   print key
   print "price: " + prices[key]
   print "stock: " + stock[key]

prices and stocks无论是对prices还是stocks ,但从来没有达到两者的连接。

这是它的工作原理:Python确实对X and Y评估。 首先它看X ,如果它是假的(ieeg False[]None ),那么表达式解析为X 只有当X不是假的(ieeg为True[1,2]42 )时,它才会返回Y

一些例子:

>>> 2 and 3
3
>>> [] and 3
[]
>>> 2 and 'hello'
'hello'
>>> [] and 'hello'
[]
>>> [] and None
[]
>>> 42 and []
[]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM