简体   繁体   English

打印链接到列表中键的字典值

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

So let's say I have a list of words:假设我有一个单词列表:

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

and a dictionary:和字典:

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

How do I get a print like this?我如何获得这样的印刷品?

apple costs 200
bee costs 100
croissant costs 450

The problem here is the alphabetical order, it is the reason I need to get the values from the dictionary using the list.这里的问题是字母顺序,这就是我需要使用列表从字典中获取值的原因。 I hope the question is understandable.我希望这个问题是可以理解的。

You don't need a list for ordering your dict, you can just use sorted to sort by key ,你不需要一个列表来排序你的字典,你可以使用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

or one liner,或一个班轮,

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