Python:按值的排序顺序打印键和值

2024-04-19 22:39:04 发布

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

我正在学习python编码,并希望获得有关排序字典的帮助。基于互联网上的可用信息,我能够找出如何按键和值对字典进行排序。但是,如果我按值排序,我很难找到排序和打印键、值对的方法。 这是我的密码:

fish = {'Chicago':300, 'San Francisco':200, 'Dallas':450, 'Seattle': 325, 'New York City': 800, 'Los Angeles':700, 'San Diego':650}
for i in sorted(fish): print (i, fish[i])

#The above loop will print the items from the dictionary in sorted order of keys.

for i in sorted(fish.items()): print (i)
#The above loop will print the items in sorted order of keys. It will print as a tuple.

for i in sorted(fish.values()): print (i)
#The above loop will print the items in sorted order by values.

#end of code

是否有一种方法可以按值的排序顺序打印字典中的键值对列表

我的结果应该是

  • 旧金山200
  • 芝加哥300
  • 西雅图325
  • 达拉斯450
  • 圣地亚哥650
  • 洛杉矶700
  • 纽约市800

其中一种方法是:

def by_value(item): return item[1]
for k, v in sorted(fish.items(), key=by_value): print (k,v)

我不想定义一个函数。我想要一个带有排序命令的for循环。有吗?我不确定lambda函数是否会这样做。我还没试过。这是我的下一步

stackoverflow给了我一个回应。看起来这是被问到和回答的。太酷了

How do I sort a dictionary by value?


Tags: the方法inloopforby字典排序