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]: odOut[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
不要介意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 892 33 04 5
python3
对于Python 3用户,需要使用.items()而不是.iteritems():
In [13]: for k, v in od.items(): print(k, v)....:1 892 33 04 5
ordered_dict = collections.OrderedDict([(k, d[k]) for k in sorted(d.keys())])
如果您需要迭代,正如上面其他人所建议的,最简单的方法是迭代排序的键。
打印按键排序的值:
# create the dictd = {k1:v1, k2:v2,...}# iterate by keys in sorted orderfor k in sorted(d.keys()):value = d[k]# do something with k, value like printprint k, value
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)
dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2}dict2 = {} # create an empty dict to store the sorted valuesfor key in sorted(dict1.keys()):if not key in dict2: # Depending on the goal, this line may not be neccessarydict2[key] = dict1[key]
更清楚地说:
dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2}dict2 = {} # create an empty dict to store the sorted valuesfor key in sorted(dict1.keys()):if not key in dict2: # Depending on the goal, this line may not be neccessaryvalue = dict1[key]dict2[key] = value