我正在学习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
是否有一种方法可以按值的排序顺序打印字典中的键值对列表
我的结果应该是
其中一种方法是:
def by_value(item): return item[1]
for k, v in sorted(fish.items(), key=by_value): print (k,v)
我不想定义一个函数。我想要一个带有排序命令的for循环。有吗?我不确定lambda函数是否会这样做。我还没试过。这是我的下一步
stackoverflow给了我一个回应。看起来这是被问到和回答的。太酷了
使用lambda值进行排序:
相关问题 更多 >
编程相关推荐