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

时间:2018-10-31 20:37:41

标签: python python-3.x list dictionary

所以说我有一个单词列表:

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

和字典:

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

我如何获得这样的印刷品?

apple costs 200
bee costs 100
croissant costs 450

这里的问题是字母顺序,这是我需要使用列表从字典中获取值的原因。我希望这个问题是可以理解的。

1 个答案:

答案 0 :(得分:1)

您不需要列表来订购字典,只需使用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']