# 字典理解值排序[重复]

#### Dictionary Comprehensions Value Sorting [duplicate]

“a”是默认顺序（字典中数据输入的顺序）。 “b”是默认顺序，但相反。 “c”是默认顺序，但按字母顺序 (AZ)。 “d”是“c”的顺序，但颠倒了（ZA）。

``````a = {"pfdee": 100, "pafeeg": 1000, "ddsds": 999, "gfgfgh": 10}
b = {i: a[i] for i in reversed(list(a.keys()))}
c = {i: a[i] for i in sorted(list(a.keys()))}
d = {i: a[i] for i in sorted(list(a.keys()), reverse=True)}

print("a: " + str(a))
print("b: " + str(b))
print("c: " + str(c))
print("d: " + str(d))
``````

3 个回复

``````a = {"pfdee": 100, "pafeeg": 1000, "ddsds": 999, "gfgfgh": 10}

e = {k : v for k, v in sorted(a.items(), key = lambda t : t[1])}
f = {k : v for k, v in sorted(a.items(), key = lambda t : t[1], reverse = True)}

print("e: " + str(e))
print("f: " + str(f))
``````

Output：

``````e: {'gfgfgh': 10, 'pfdee': 100, 'ddsds': 999, 'pafeeg': 1000}
f: {'pafeeg': 1000, 'ddsds': 999, 'pfdee': 100, 'gfgfgh': 10}
``````

``````e = dict(sorted(a.items(), key = lambda t : t[1]))
f = dict(sorted(a.items(), key = lambda t : t[1], reverse = True))
``````

sorted 接受一个可选参数，称为 key，因此您可以指定一个 function，它返回一个 integer，通过它对元素进行排序。

``````e = {i: a[i] for i in sorted(list(a.keys(), key = lambda e: len(e))}
f = {i: a[i] for i in sorted(list(a.keys(), key = lambda e: -len(e))}
``````

``````a = {"pfdee": 100, "pafeeg": 1000, "ddsds": 999, "gfgfgh": 10}
b = {i: a[i] for i in reversed(list(a.keys()))}
c = {i: a[i] for i in sorted(list(a.keys()))}
d = {i: a[i] for i in sorted(list(a.keys()), reverse=True)}
e = {i: a[i] for i in sorted(a.keys(),key=len)}
f = {i: a[i] for i in sorted(a.keys(),key=len,reverse=True)}
print("a: " + str(a))
print("b: " + str(b))
print("c: " + str(c))
print("d: " + str(d))
print("e: " + str(e))
``````
1 按值对字典排序[重复]

2 按值对字典排序[重复]

3 按值对字典排序[重复]

2013-03-05 11:59:41 2 1499   c#/ mono
4 可以在字典理解期间过滤重复值吗？

6 如何按字典值对列表排序？ [重复]

7 字典值排序错误[重复]

8 将字典值按降序排序[重复]

2020-05-11 02:17:33 1 58   c#
9 根据列表对字典的值排序[重复]

10 如何按值的升序对字典排序？ [重复]