[英]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]
這將僅循環兩個字典中存在的那些鍵。
假設prices
和stock
之間的密鑰總是相同的,您可以簡單地這樣做:
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.