繁体   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