如何按键对字典进行排序?
示例输入:
{2:3, 1:89, 4:5, 3:0}
期望的输出:
{1:89, 2:3, 3:0, 4:5}
如何按键对字典进行排序?
示例输入:
{2:3, 1:89, 4:5, 3:0}
期望的输出:
{1:89, 2:3, 3:0, 4:5}
当前回答
有许多Python模块提供字典实现,这些字典自动按排序顺序维护键。考虑sortedcontainers模块,它是纯python和像c一样快的实现。此外,还会与其他受欢迎的选项进行性能比较。
如果您需要在迭代的同时不断地添加和删除键/值对,那么使用有序字典是一个不合适的解决方案。
>>> from sortedcontainers import SortedDict
>>> d = {2:3, 1:89, 4:5, 3:0}
>>> s = SortedDict(d)
>>> s.items()
[(1, 89), (2, 3), (3, 0), (4, 5)]
SortedDict类型还支持索引位置查找和删除,这在内置dict类型中是不可能的。
>>> s.iloc[-1]
4
>>> del s.iloc[2]
>>> s.keys()
SortedSet([1, 2, 4])
其他回答
Python字典在Python 3.6之前是无序的。在Python 3.6的CPython实现中,字典保持插入顺序。 从Python 3.7开始,这将成为一种语言特性。
在Python 3.6的更新日志(https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-compactdict):
考虑了这个新实现的保序方面 一个实现细节,不应该依赖(这可能 将来会有变化,但希望有这个新词典 在语言中实现了几个版本,然后才更改 语言规范要求所有当前的语义保持有序 以及未来的Python实现;这也有助于保存 向后兼容该语言的旧版本 随机迭代顺序仍然有效,例如Python 3.5)。
Python 3.7文档(https://docs.python.org/3.7/tutorial/datastructures.html#dictionaries):
在字典上执行list(d)将返回所有使用的键的列表 在字典中,按插入顺序(如果你想排序,只需使用 排序(d))。
因此,与以前的版本不同,您可以在Python 3.6/3.7之后对字典进行排序。如果你想对包含子字典在内的嵌套字典进行排序,你可以这样做:
test_dict = {'a': 1, 'c': 3, 'b': {'b2': 2, 'b1': 1}}
def dict_reorder(item):
return {k: dict_reoder(v) if isinstance(v, dict) else v for k, v in sorted(item.items())}
reordered_dict = dict_reorder(test_dict)
https://gist.github.com/ligyxy/f60f0374defc383aa098d44cfbd318eb
from operator import itemgetter
# if you would like to play with multiple dictionaries then here you go:
# Three dictionaries that are composed of first name and last name.
user = [
{'fname': 'Mo', 'lname': 'Mahjoub'},
{'fname': 'Abdo', 'lname': 'Al-hebashi'},
{'fname': 'Ali', 'lname': 'Muhammad'}
]
# This loop will sort by the first and the last names.
# notice that in a dictionary order doesn't matter. So it could put the first name first or the last name first.
for k in sorted (user, key=itemgetter ('fname', 'lname')):
print (k)
# This one will sort by the first name only.
for x in sorted (user, key=itemgetter ('fname')):
print (x)
Python字典是无序的。通常,这不是问题,因为最常见的用例是执行查找。
最简单的方法是创建一个集合。OrderedDict以排序顺序插入元素。
ordered_dict = collections.OrderedDict([(k, d[k]) for k in sorted(d.keys())])
如果需要迭代,就像上面其他人建议的那样,最简单的方法是迭代排序的键。的例子,
按键排序打印值:
# create the dict
d = {k1:v1, k2:v2,...}
# iterate by keys in sorted order
for k in sorted(d.keys()):
value = d[k]
# do something with k, value like print
print k, value
获取按键排序的值列表:
values = [d[k] for k in sorted(d.keys())]
我的建议是这样的,因为它允许你在添加项和将来可能需要添加项时对字典排序或保持字典排序:
从头开始构建词典。有第二个数据结构,一个包含键列表的列表。bisect包有一个insort函数,允许插入到一个排序的列表中,或者在完全填充字典后对列表进行排序。现在,当您迭代字典时,您将迭代列表以按顺序访问每个键,而不用担心字典结构的表示(它不是为排序而设计的)。
如果你知道你所有的键都是相同的类型,或者有支持'< '(小于,python的__lt__)的类型,那么你可以使用dict(sorted(your_dict.items(), key=lambda _: _[0]))一个容易理解的一行程序