打印链接到lis中键的字典值

2024-06-25 06:35:35 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个单词列表:

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

还有一本字典:

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

我怎样才能得到这样的照片

apple costs 200
bee costs 100
croissant costs 450

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


Tags: apple列表字典顺序字母原因单词照片
1条回答
网友
1楼 · 发布于 2024-06-25 06:35:35

您不需要为dict排序的列表,您可以使用sortedkey排序

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

相关问题 更多 >