发布于 1年前
Python 用键值对字典进行排序
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
result = {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
print(result)
# {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
result = {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
print(result)
# {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}