字典按value排序

阅读 156

2022-04-17

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)

0 0 举报