我怎样用钥匙对字典排序?

时间:2022-11-06 07:44:15

What would be a nice way to go from {2:3, 1:89, 4:5, 3:0} to {1:89, 2:3, 3:0, 4:5}?
I checked some posts but they all use the "sorted" operator that returns tuples.

从{2:3,1:89,4:5,3:0}到{1:89,2:3,3:0,4:5},有什么好方法?我检查了一些帖子,但他们都使用返回元组的“排序”操作符。

22 个解决方案

#1


665  

Standard Python dictionaries are unordered. Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a dict in a way that would preserve the ordering.

标准的Python字典是无序的。即使您对(键、值)对进行了排序,您也无法将它们存储在命令中,以保存排序。

The easiest way is to use OrderedDict, which remembers the order in which the elements have been inserted:

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

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)])

Never mind the way od is printed out; it'll work as expected:

不用管od是怎么打印出来的;它会正常工作:

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

For Python 3 users, one needs to use the .items() instead of .iteritems():

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

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

#2


323  

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:

在Python 2.4及以上版本中:

mydict = {'carl':40,
          'alan':2,
          'bob':1,
          'danny':3}

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

gives:

给:

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

(Python below 2.4:)

(下面的Python 2.4:)

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

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

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

#3


157  

From Python's collections library documentation:

从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)])

#4


31  

There are a number of Python modules that provide dictionary implementations which automatically maintain the keys in sorted order. Consider the sortedcontainers module which is pure-Python and fast-as-C implementations. There is also a performance comparison with other popular options benchmarked against one another.

有许多Python模块提供字典实现,它们自动地按顺序维护键。考虑一下sortedcontainer模块,它是pure-Python和quick -as- c实现。还有一个性能比较,与其他流行的选项对比。

Using an ordered dict is an inadequate solution if you need to constantly add and remove key/value pairs while also iterating.

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

>>> 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)]

The SortedDict type also supports indexed location lookups and deletion which isn't possible with the built-in dict type.

SortedDict类型还支持索引位置查找和删除,这在内置命令类型中是不可能的。

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

#5


23  

Simply:

简单:

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

for k,v in sd:
    print k, v

Output:

输出:

1 89
2 3
3 0
4 5

#6


20  

As others have mentioned, dictionaries are inherently unordered. However, if the issue is merely displaying dictionaries in an ordered fashion, you can override the __str__ method in a dictionary subclass, and use this dictionary class rather than the builtin dict. Eg.

正如其他人所提到的,字典本身就是无序的。但是,如果问题仅仅是按照有序的方式显示字典,那么您可以在dictionary子类中重写__str__方法,并使用这个字典类而不是builtin dict。

class SortedDisplayDict(dict):
   def __str__(self):
       return "{" + ", ".join("%r: %r" % (key, self[key]) for key in sorted(self)) + "}"


>>> d = SortedDisplayDict({2:3, 1:89, 4:5, 3:0})
>>> d
{1: 89, 2: 3, 3: 0, 4: 5}

Note, this changes nothing about how the keys are stored, the order they will come back when you iterate over them etc, just how they're displayed with print or at the python console.

注意,这不会改变密钥的存储方式,当您迭代它们时,它们将返回的顺序,等等,它们是如何显示与print或在python控制台上的。

#7


14  

The most concise way that is not mentioned in any of the other answers is probably this one:

在其他答案中没有提到的最简洁的方法可能是这个:

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

#8


13  

Found another way:

发现了另一种方式:

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

upd:
1. this also sorts nested objects (thanks @DanielF).
2. python dictionaries are unordered therefore this is sutable for print or assign to str only.

乌利希期刊指南:1。这也可以对嵌套的对象进行排序(感谢@DanielF)。2。python字典是无序的,因此这是用于打印或分配给str的sutable。

#9


11  

In Python 3.

Python 3。

>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
    print (key, D1[key])

gives

给了

1 89
2 3
3 0
4 5

#10


8  

Here I found some simplest solution to sort the python dict by key using pprint. eg.

在这里,我找到了一些最简单的解决方案,通过使用pprint来对python命令进行排序。如。

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

but while using pprint it will return sorted dict

但是在使用pprint时,它会返回排序的命令。

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

#11


5  

There is an easy way to sort a dictionary.

有一种简单的方法来分类字典。

According to your question,

根据你的问题,

The solution is :

解决方案是:

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

(Where c,is the name of your dictionary.)

(c,是你的字典的名字。)

This program gives the following output:

该程序给出如下输出:

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

like u wanted.

就像你想要的。

Another example is:

另一个例子是:

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

Gives the output:['Albert', 'Bill', 'John', 'Lucy', 'Peter']

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

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

Gives the output:[18, 24, 32, 36, 41]

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

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

Gives the output:

给出了输出:

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

Hence by changing it into keys, values and items , you can print like what u wanted.Hope this helps!

因此,通过将其转换为键、值和项,您可以像您希望的那样打印。希望这可以帮助!

#12


4  

Python dicts are un-ordered. Usually, this is not a problem since the most common use case is to do a lookup.

Python字典un-ordered。通常,这不是问题,因为最常见的用例是查找。

The simplest way to do what you want would be to create a collections.OrderedDict inserting the elements in sorted order.

最简单的方法就是创建一个集合。OrderedDict将元素插入到已排序的顺序中。

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

If you need to iterated, as others above have suggested, the simplest way would be to iterate over sorted keys. Examples-

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

Print values sorted by 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

Get list of values sorted by keys:

获取按键排序的值列表:

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

#13


2  

Will generate exactly what you want:

将产生你想要的:

 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}

But this is not the write way to do this, because, It could show a distinct behavior with different dictionaries , which I have learned recently. Hence perfect way has been suggested by Tim In the response of my Query which I am sharing here.

但这不是写的方式,因为,它可以用不同的字典显示不同的行为,这是我最近学过的。因此,Tim在我的查询的回复中提出了完美的方法。

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

#14


2  

I think the easiest thing is to sort the dict by key and save the sorted key:value pair in a new dict.

我认为最简单的方法是按键排序,并保存排序键:在新命令中值对。

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]

To make it clearer:

使它更清晰:

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

#15


2  

Python dictionary was unordered before Python 3.6. In CPython implementation of Python 3.6, dictionary keeps the insertion order. From Python 3.7, this will become a language feature.

在Python 3.6之前,Python字典是无序的。在Python 3.6的CPython实现中,dictionary保持插入顺序。从Python 3.7中,这将成为一种语言特性。

If you want to sort a nested dict including the sub-dict inside, you can do:

如果你想对嵌套的命令进行排序,包括里面的子命令,你可以这样做:

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

def dict_reorder(item):
    if isinstance(item, dict):
        item = {k: v for k, v in sorted(item.items())}
        for k, v in item.items():
            if isinstance(v, dict):
                item[k] = dict_reorder(v)
    return item

reordered_dict = dict_reorder(test_dict)

https://gist.github.com/ligyxy/f60f0374defc383aa098d44cfbd318eb

https://gist.github.com/ligyxy/f60f0374defc383aa098d44cfbd318eb

#16


0  

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

伙计们,你们把事情弄得很复杂…这是很简单的

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

The output is:

的输出是:

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

#17


0  

A timing comparison of the two methods in 2.7 shows them to be virtually identical:

两种方法的时间比较在2.7显示它们几乎是相同的:

>>> 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\n"
>>> setup_string += "a = OrderedDict({1:89, 2:3, 3:0, 4:5})\n"
>>> setup_string += "b = a.items()"
>>> timeit.timeit(stmt="[(k, val) for k, val in b]", setup=setup_string, number=10000)
0.003581275490432745 

#18


0  

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)

#19


0  

Simplest solution is that you should get a list of dict key is sorted order and then iterate over dict. For example

最简单的解决方案是,您应该得到一个dict键的列表,它是有序的,然后遍历字典。

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]

Following will be the output (desending order)

以下将是输出(取消订单)

e 30
b 13
d 4
c 2
a 1

#20


0  

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]}

#21


-2  

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)

#22


-7  

If you have a dict, for example:

如果你有一个法令,例如:

not_ordered_dict = {5 : "5555", 9 : "9999", 1 : "1111"}

ordered_dict = {}

for key in sorted(not_ordered_dict):
    ordered_dict[key] = not_ordered_dict[key]   

#1


665  

Standard Python dictionaries are unordered. Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a dict in a way that would preserve the ordering.

标准的Python字典是无序的。即使您对(键、值)对进行了排序,您也无法将它们存储在命令中,以保存排序。

The easiest way is to use OrderedDict, which remembers the order in which the elements have been inserted:

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

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)])

Never mind the way od is printed out; it'll work as expected:

不用管od是怎么打印出来的;它会正常工作:

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

For Python 3 users, one needs to use the .items() instead of .iteritems():

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

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

#2


323  

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:

在Python 2.4及以上版本中:

mydict = {'carl':40,
          'alan':2,
          'bob':1,
          'danny':3}

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

gives:

给:

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

(Python below 2.4:)

(下面的Python 2.4:)

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

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

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

#3


157  

From Python's collections library documentation:

从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)])

#4


31  

There are a number of Python modules that provide dictionary implementations which automatically maintain the keys in sorted order. Consider the sortedcontainers module which is pure-Python and fast-as-C implementations. There is also a performance comparison with other popular options benchmarked against one another.

有许多Python模块提供字典实现,它们自动地按顺序维护键。考虑一下sortedcontainer模块,它是pure-Python和quick -as- c实现。还有一个性能比较,与其他流行的选项对比。

Using an ordered dict is an inadequate solution if you need to constantly add and remove key/value pairs while also iterating.

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

>>> 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)]

The SortedDict type also supports indexed location lookups and deletion which isn't possible with the built-in dict type.

SortedDict类型还支持索引位置查找和删除,这在内置命令类型中是不可能的。

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

#5


23  

Simply:

简单:

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

for k,v in sd:
    print k, v

Output:

输出:

1 89
2 3
3 0
4 5

#6


20  

As others have mentioned, dictionaries are inherently unordered. However, if the issue is merely displaying dictionaries in an ordered fashion, you can override the __str__ method in a dictionary subclass, and use this dictionary class rather than the builtin dict. Eg.

正如其他人所提到的,字典本身就是无序的。但是,如果问题仅仅是按照有序的方式显示字典,那么您可以在dictionary子类中重写__str__方法,并使用这个字典类而不是builtin dict。

class SortedDisplayDict(dict):
   def __str__(self):
       return "{" + ", ".join("%r: %r" % (key, self[key]) for key in sorted(self)) + "}"


>>> d = SortedDisplayDict({2:3, 1:89, 4:5, 3:0})
>>> d
{1: 89, 2: 3, 3: 0, 4: 5}

Note, this changes nothing about how the keys are stored, the order they will come back when you iterate over them etc, just how they're displayed with print or at the python console.

注意,这不会改变密钥的存储方式,当您迭代它们时,它们将返回的顺序,等等,它们是如何显示与print或在python控制台上的。

#7


14  

The most concise way that is not mentioned in any of the other answers is probably this one:

在其他答案中没有提到的最简洁的方法可能是这个:

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

#8


13  

Found another way:

发现了另一种方式:

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

upd:
1. this also sorts nested objects (thanks @DanielF).
2. python dictionaries are unordered therefore this is sutable for print or assign to str only.

乌利希期刊指南:1。这也可以对嵌套的对象进行排序(感谢@DanielF)。2。python字典是无序的,因此这是用于打印或分配给str的sutable。

#9


11  

In Python 3.

Python 3。

>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
    print (key, D1[key])

gives

给了

1 89
2 3
3 0
4 5

#10


8  

Here I found some simplest solution to sort the python dict by key using pprint. eg.

在这里,我找到了一些最简单的解决方案,通过使用pprint来对python命令进行排序。如。

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

but while using pprint it will return sorted dict

但是在使用pprint时,它会返回排序的命令。

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

#11


5  

There is an easy way to sort a dictionary.

有一种简单的方法来分类字典。

According to your question,

根据你的问题,

The solution is :

解决方案是:

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

(Where c,is the name of your dictionary.)

(c,是你的字典的名字。)

This program gives the following output:

该程序给出如下输出:

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

like u wanted.

就像你想要的。

Another example is:

另一个例子是:

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

Gives the output:['Albert', 'Bill', 'John', 'Lucy', 'Peter']

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

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

Gives the output:[18, 24, 32, 36, 41]

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

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

Gives the output:

给出了输出:

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

Hence by changing it into keys, values and items , you can print like what u wanted.Hope this helps!

因此,通过将其转换为键、值和项,您可以像您希望的那样打印。希望这可以帮助!

#12


4  

Python dicts are un-ordered. Usually, this is not a problem since the most common use case is to do a lookup.

Python字典un-ordered。通常,这不是问题,因为最常见的用例是查找。

The simplest way to do what you want would be to create a collections.OrderedDict inserting the elements in sorted order.

最简单的方法就是创建一个集合。OrderedDict将元素插入到已排序的顺序中。

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

If you need to iterated, as others above have suggested, the simplest way would be to iterate over sorted keys. Examples-

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

Print values sorted by 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

Get list of values sorted by keys:

获取按键排序的值列表:

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

#13


2  

Will generate exactly what you want:

将产生你想要的:

 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}

But this is not the write way to do this, because, It could show a distinct behavior with different dictionaries , which I have learned recently. Hence perfect way has been suggested by Tim In the response of my Query which I am sharing here.

但这不是写的方式,因为,它可以用不同的字典显示不同的行为,这是我最近学过的。因此,Tim在我的查询的回复中提出了完美的方法。

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

#14


2  

I think the easiest thing is to sort the dict by key and save the sorted key:value pair in a new dict.

我认为最简单的方法是按键排序,并保存排序键:在新命令中值对。

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]

To make it clearer:

使它更清晰:

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

#15


2  

Python dictionary was unordered before Python 3.6. In CPython implementation of Python 3.6, dictionary keeps the insertion order. From Python 3.7, this will become a language feature.

在Python 3.6之前,Python字典是无序的。在Python 3.6的CPython实现中,dictionary保持插入顺序。从Python 3.7中,这将成为一种语言特性。

If you want to sort a nested dict including the sub-dict inside, you can do:

如果你想对嵌套的命令进行排序,包括里面的子命令,你可以这样做:

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

def dict_reorder(item):
    if isinstance(item, dict):
        item = {k: v for k, v in sorted(item.items())}
        for k, v in item.items():
            if isinstance(v, dict):
                item[k] = dict_reorder(v)
    return item

reordered_dict = dict_reorder(test_dict)

https://gist.github.com/ligyxy/f60f0374defc383aa098d44cfbd318eb

https://gist.github.com/ligyxy/f60f0374defc383aa098d44cfbd318eb

#16


0  

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

伙计们,你们把事情弄得很复杂…这是很简单的

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

The output is:

的输出是:

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

#17


0  

A timing comparison of the two methods in 2.7 shows them to be virtually identical:

两种方法的时间比较在2.7显示它们几乎是相同的:

>>> 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\n"
>>> setup_string += "a = OrderedDict({1:89, 2:3, 3:0, 4:5})\n"
>>> setup_string += "b = a.items()"
>>> timeit.timeit(stmt="[(k, val) for k, val in b]", setup=setup_string, number=10000)
0.003581275490432745 

#18


0  

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)

#19


0  

Simplest solution is that you should get a list of dict key is sorted order and then iterate over dict. For example

最简单的解决方案是,您应该得到一个dict键的列表,它是有序的,然后遍历字典。

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]

Following will be the output (desending order)

以下将是输出(取消订单)

e 30
b 13
d 4
c 2
a 1

#20


0  

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]}

#21


-2  

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)

#22


-7  

If you have a dict, for example:

如果你有一个法令,例如:

not_ordered_dict = {5 : "5555", 9 : "9999", 1 : "1111"}

ordered_dict = {}

for key in sorted(not_ordered_dict):
    ordered_dict[key] = not_ordered_dict[key]