[英]How to print keys and values of a dictionary which is contained in a list in Python
[英]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.