python 按值排序字典

x = {'x':20,'a':12,'b':5}
keys = sorted(x.keys())
for key in keys:
print(f"{key}:{x[key]}")

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

按值降序排列

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

你可能感兴趣的:(python 按值排序字典)