# 我怎样才能按键sorting字典？

`{2:3, 1:89, 4:5, 3:0}``{1:89, 2:3, 3:0, 4:5}`是一个很好的方法吗？

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

` `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

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

` `mydict = {'carl':40, 'alan':2, 'bob':1, 'danny':3} for key in sorted(mydict): print "%s: %s" % (key, mydict[key])` `

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

（Python低于2.4）

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

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

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

SortedDicttypes还支持索引位置查找和删除，这对于内置的字典types是不可能的。

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

` `d = {2:3, 1:89, 4:5, 3:0} sd = sorted(d.items()) for k,v in sd: print k, v` `

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

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

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

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

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

UPD：
1.这也sorting嵌套的对象（谢谢@DanielF）。
2. python字典是无序的，因此这是可打印的或只分配给str。

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

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

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

（其中c是你的字典的名字）

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

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

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

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

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

Python字典是无序的。 通常，这不是一个问题，因为最常见的用例是查找。

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

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

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

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

` `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` `

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

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

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

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

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

` `e 30 b 13 d 4 c 2 a 1` `
` `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]}` `
` `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)` `

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