Skip to main content
 首页 » 编程设计

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

2024年12月31日13jpfss

假设我有一个单词列表:

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']