簡體   English   中英

打印鏈接到列表中鍵的字典值

[英]Print dictionary values linked to keys which are in a list

假設我有一個單詞列表:

listA = ['apple', 'bee', 'croissant']

和字典:

dictA = {'bee': '100', 'apple': '200', 'croissant': '450'}

我如何獲得這樣的印刷品?

apple costs 200
bee costs 100
croissant costs 450

這里的問題是字母順序,這就是我需要使用列表從字典中獲取值的原因。 我希望這個問題是可以理解的。

你不需要一個列表來排序你的字典,你可以使用sorted key排序,

dictA = {'bee': '100', 'apple': '200', 'croissant': '450'}

for key in sorted(dictA):
    print ("{} costs {}".format(key, dictA[key]))

# output,

apple costs 200
bee costs 100
croissant costs 450

或一個班輪,

print (sorted("{} costs {}".format(key, dictA[key]) for key in dictA))

#  output,
['apple costs 200', 'bee costs 100', 'croissant costs 450']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM