如何按键对字典进行排序?

示例输入:

{2:3, 1:89, 4:5, 3:0}

期望的输出:

{1:89, 2:3, 3:0, 4:5}

当前回答

l = dict.keys()
l2 = l
l2.append(0)
l3 = []
for repeater in range(0, len(l)):
    smallnum = float("inf")
    for listitem in l2:
        if listitem < smallnum:
            smallnum = listitem
    l2.remove(smallnum)
    l3.append(smallnum)
l3.remove(0)
l = l3

for listitem in l:
    print(listitem)

其他回答

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的__lt__)的类型,那么你可以使用dict(sorted(your_dict.items(), key=lambda _: _[0]))一个容易理解的一行程序

以下是建议解决方案的性能:

from collections import OrderedDict
from sortedcontainers import SortedDict
import json

keys = np.random.rand(100000)
vals = np.random.rand(100000)

d = dict(zip(keys, vals))

timeit SortedDict(d)
#45.8 ms ± 780 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

timeit sorted(d.items())
#91.9 ms ± 707 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

timeit OrderedDict(sorted(d.items(), key=lambda x: x[0]))
#93.7 ms ± 1.52 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

timeit dict(sorted(dic.items()))
#113 ms ± 824 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

timeit OrderedDict(sorted(dic.items()))
#122 ms ± 2.65 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

timeit json.dumps(d, sort_keys=True)
#259 ms ± 9.42 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

如我们所见,格兰特·詹克斯的解决方案是目前为止最快的。

来自Python的集合库文档:

>>> from collections import OrderedDict

>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key -- OrderedDict(sorted(d.items()) also works
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])

对于CPython/PyPy 3.6,以及任何Python 3.7或更高版本,这很容易做到:

>>> d = {2:3, 1:89, 4:5, 3:0}
>>> dict(sorted(d.items()))
{1: 89, 2: 3, 3: 0, 4: 5}