关于python:如何按键对字典进行排序?

How can I sort a dictionary by key?

{2:3, 1:89, 4:5, 3:0}{1:89, 2:3, 3:0, 4:5}有什么好办法?我检查了一些文章,但它们都使用返回元组的"sorted"操作符。


标准的python字典是无序的。即使对(键、值)对进行了排序,也无法以保留排序的方式将它们存储在dict中。

最简单的方法是使用OrderedDict,它记住元素插入的顺序:

1
2
3
4
5
6
7
8
In [1]: import collections

In [2]: d = {2:3, 1:89, 4:5, 3:0}

In [3]: od = collections.OrderedDict(sorted(d.items()))

In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])

别在意od的打印方式,它会按预期工作:

1
2
3
4
5
6
7
8
9
10
11
12
In [11]: od[1]
Out[11]: 89

In [12]: od[3]
Out[12]: 0

In [13]: for k, v in od.iteritems(): print k, v
   ....:
1 89
2 3
3 0
4 5

Python 3

对于python 3用户,需要使用.items()而不是.iteritems()

1
2
3
4
5
6
In [13]: for k, v in od.items(): print(k, v)
   ....:
1 89
2 3
3 0
4 5


Dictionaries themselves do not have ordered items as such, should you want to print them etc to some order, here are some examples:

In Python 2.4 and above:

1
2
3
4
5
6
7
mydict = {'carl':40,
          'alan':2,
          'bob':1,
          'danny':3}

for key in sorted(mydict):
    print"%s: %s" % (key, mydict[key])

给予:

1
2
3
4
alan: 2
bob: 1
carl: 40
danny: 3

(2.4以下的python:)

1
2
3
4
keylist = mydict.keys()
keylist.sort()
for key in keylist:
    print"%s: %s" % (key, mydict[key])

来源:http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/


来自python的collections库文档:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> 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)])


对于python3.6+,这很容易通过以下方式完成:

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


有许多python模块提供字典实现,自动按排序顺序维护键。考虑SortedContainers模块,它是纯python和fast-as-c实现。也有一个性能比较与其他流行的选择基准彼此。

如果您需要在进行迭代的同时不断地添加和删除键/值对,那么使用有序dict是一个不充分的解决方案。

1
2
3
4
5
>>> 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类型中是不可能的。

1
2
3
4
5
>>> s.iloc[-1]
4
>>> del s.iloc[2]
>>> s.keys()
SortedSet([1, 2, 4])


简单地说:

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

for k,v in sd:
    print k, v

输出:

1
2
3
4
1 89
2 3
3 0
4 5


正如其他人所提到的,字典本身就是无序的。但是,如果问题仅仅是按顺序显示字典,则可以重写字典子类中的__str__方法,并使用此字典类而不是内置的dict。如。

1
2
3
4
5
6
class SortedDisplayDict(dict):
   def __str__(self):
       return"{" +",".join("%r: %r" % (key, self[key]) for key in sorted(self)) +
<hr><P>在Python 3中。</P>[cc lang="python"]>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
    print (key, D1[key])

给予

1
2
3
4
1 89
2 3
3 0
4 5

找到另一种方法:

1
2
import json
print json.dumps(d, sort_keys = True)

UPD:1。这还会对嵌套对象进行排序(谢谢@danielf)。2。python字典是无序的,因此它只能用于打印或分配给str。


在这里,我找到了一些使用pprint按键对python dict排序的最简单解决方案。如。

1
2
3
>>> x = {'a': 10, 'cd': 20, 'b': 30, 'az': 99}
>>> print x
{'a': 10, 'b': 30, 'az': 99, 'cd': 20}

但在使用pprint时,它将返回排序的dict

1
2
3
>>> import pprint
>>> pprint.pprint(x)
{'a': 10, 'az': 99, 'b': 30, 'cd': 20}

python字典在python 3.6之前是无序的。在python 3.6的cpython实现中,字典保持插入顺序。从Python3.7开始,这将成为一个语言特性。

在python 3.6的changelog中(https://docs.python.org/3.6/whatsnew/3.6.html whatsnew36 compactdict):

The order-preserving aspect of this new implementation is considered
an implementation detail and should not be relied upon (this may
change in the future, but it is desired to have this new dict
implementation in the language for a few releases before changing the
language spec to mandate order-preserving semantics for all current
and future Python implementations; this also helps preserve
backwards-compatibility with older versions of the language where
random iteration order is still in effect, e.g. Python 3.5).

在python 3.7文档(https://docs.python.org/3.7/tutorial/datastructures.html字典)中:

Performing list(d) on a dictionary returns a list of all the keys used
in the dictionary, in insertion order (if you want it sorted, just use
sorted(d) instead).

因此,与以前的版本不同,您可以在python 3.6/3.7之后对dict进行排序。如果要对嵌套的dict(包括内部的子dict)进行排序,可以执行以下操作:

1
2
3
4
5
6
test_dict = {'a': 1, 'c': 3, 'b': {'b2': 2, 'b1': 1}}

def dict_reorder(item):
    return {k: sort_dict(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


有一种简单的方法可以对字典进行排序。

根据你的问题,

解决方案是:

1
2
3
c={2:3, 1:89, 4:5, 3:0}
y=sorted(c.items())
print y

(其中c是字典的名称。)

此程序提供以下输出:

1
[(1, 89), (2, 3), (3, 0), (4, 5)]

就像你想要的一样。

另一个例子是:

1
2
3
d={"John":36,"Lucy":24,"Albert":32,"Peter":18,"Bill":41}
x=sorted(d.keys())
print x

给出输出:['Albert', 'Bill', 'John', 'Lucy', 'Peter']

1
2
y=sorted(d.values())
print y

给出输出:[18, 24, 32, 36, 41]

1
2
z=sorted(d.items())
print z

给出输出:

1
[('Albert', 32), ('Bill', 41), ('John', 36), ('Lucy', 24), ('Peter', 18)]

因此,通过将其更改为键、值和项,您可以像您想要的那样进行打印。希望这有帮助!


将生成您想要的:

1
2
3
4
5
6
7
8
9
10
 D1 = {2:3, 1:89, 4:5, 3:0}

 sort_dic = {}

 for i in sorted(D1):
     sort_dic.update({i:D1[i]})
 print sort_dic


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

但这不是写的方式,因为它可以显示不同字典的不同行为,这是我最近学到的。因此,蒂姆在回答我在这里分享的问题时提出了完美的方法。

1
2
from collections import OrderedDict
sorted_dict = OrderedDict(sorted(D1.items(), key=lambda t: t[0]))

我认为最简单的方法是按键对dict进行排序,并将排序后的key:value对保存到新的dict中。

1
2
3
4
5
dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2}
dict2 = {}                  # create an empty dict to store the sorted values
for key in sorted(dict1.keys()):
    if not key in dict2:    # Depending on the goal, this line may not be neccessary
        dict2[key] = dict1[key]

更清楚地说:

1
2
3
4
5
6
dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2}
dict2 = {}                  # create an empty dict to store the sorted     values
for key in sorted(dict1.keys()):
    if not key in dict2:    # Depending on the goal, this line may not be  neccessary
        value = dict1[key]
        dict2[key] = value


可以根据问题按键对当前词典进行排序,从而创建新词典。

这是你的字典

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

通过使用lambda函数对该数据进行排序,创建新字典d1

1
d1 = dict(sorted(d.items(), key = lambda x:x[0]))

d1应该是1:89,2:3,3:0,4:5,根据d中的键排序。


python dicts是无序的。通常,这不是问题,因为最常见的用例是进行查找。

最简单的方法就是创建一个collections.OrderedDict,按排序顺序插入元素。

1
ordered_dict = collections.OrderedDict([(k, d[k]) for k in sorted(d.keys())])

如果您需要迭代,正如上面其他人所建议的,最简单的方法是迭代排序后的键。实例-

按键排序的打印值:

1
2
3
4
5
6
7
# 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

获取按键排序的值列表:

1
values = [d[k] for k in sorted(d.keys())]


我想出了单行听写排序。

1
2
3
4
5
>> a = {2:3, 1:89, 4:5, 3:0}
>> c = {i:a[i] for i in sorted(a.keys())}
>> print(c)
{1: 89, 2: 3, 3: 0, 4: 5}
[Finished in 0.4s]

希望这会有所帮助。


Guys you are making things complicated ... it's really simple

1
2
3
from pprint import pprint
Dict={'B':1,'A':2,'C':3}
pprint(Dict)

输出是:

1
{'A':2,'B':1,'C':3}


最简单的解决方案是,您应该得到一个dict键列表,它是按顺序排序的,然后在dict上迭代。

1
2
3
4
a1 = {'a':1, 'b':13, 'd':4, 'c':2, 'e':30}
a1_sorted_keys = sorted(a1, key=a1.get, reverse=True)
for r in a1_sorted_keys:
    print r, a1[r]

以下为输出(下降顺序)

1
2
3
4
5
e 30
b 13
d 4
c 2
a 1


2.7中两种方法的时间比较表明它们几乎相同:

1
2
3
4
5
6
7
8
9
10
11
>>> setup_string ="a = sorted(dict({2:3, 1:89, 4:5, 3:0}).items())"
>>> timeit.timeit(stmt="[(k, val) for k, val in a]", setup=setup_string, number=10000)
0.003599141953657181

>>> setup_string ="from collections import OrderedDict
"

>>> setup_string +="a = OrderedDict({1:89, 2:3, 3:0, 4:5})
"

>>> setup_string +="b = a.items()"
>>> timeit.timeit(stmt="[(k, val) for k, val in b]", setup=setup_string, number=10000)
0.003581275490432745

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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)

1
2
3
4
5
6
7
dictionary = {1:[2],2:[],5:[4,5],4:[5],3:[1]}

temp=sorted(dictionary)
sorted_dict = dict([(k,dictionary[k]) for i,k in enumerate(temp)])

sorted_dict:
         {1: [2], 2: [], 3: [1], 4: [5], 5: [4, 5]}

或者使用pandas

演示:

1
2
3
4
5
6
7
>>> d={'B':1,'A':2,'C':3}
>>> df=pd.DataFrame(d,index=[0]).sort_index(axis=1)
   A  B  C
0  2  1  3
>>> df.to_dict('int')[0]
{'A': 2, 'B': 1, 'C': 3}
>>>

见:

Docs of this

Documentation of whole pandas


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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)


如果您有听写,例如:

[cc lang="python"]not_ordered_dict = {5 :"5555", 9 :"9999", 1 :"1111