0
点赞
收藏
分享

微信扫一扫

字典按value排序

那小那小 2022-04-17 阅读 154
python
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}

print(x.items()) # list of tuples

print(sorted(x.items(), key=lambda item: item[1])) # sorted list of tuples

print(dict(sorted(x.items(), key=lambda item: item[1]))) # sorted dict 

# or

print({k: v for k, v in sorted(x.items(), key=lambda item: item[1])}) # sorted dict

output:

dict_items([(1, 2), (3, 4), (4, 3), (2, 1), (0, 0)])
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

ref

How do I sort a dictionary by value?

举报

相关推荐

0 条评论