与列表不同的字典没有排序(并且没有“排序”属性)。因此,您无法依赖首次添加时按相同顺序获取项目。在Python中,如何轻松地从字典中检索已排序的项目?
什么是循环包含字符串作为键值的字典并按键升序检索它们的最简单方法是什么?
例如,你有这样的:
d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
我想通过键排序按以下顺序打印相关的值:
this is a
this is b
this is c
与列表不同的字典没有排序(并且没有“排序”属性)。因此,您无法依赖首次添加时按相同顺序获取项目。在Python中,如何轻松地从字典中检索已排序的项目?
什么是循环包含字符串作为键值的字典并按键升序检索它们的最简单方法是什么?
例如,你有这样的:
d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
我想通过键排序按以下顺序打印相关的值:
this is a
this is b
this is c
这个片段将这样做。如果你打算经常这样做,你可能需要制作一个“分类键”方法或其他方法,以便让眼睛更轻松。
keys = list(d.keys())
keys.sort()
for key in keys:
print d[key]
编辑:dF的解决方案更好 - 我忘了所有关于排序()。
你的意思是说你需要按键值排序的值吗? 在这种情况下,这应该这样做:
for key in sorted(d):
print d[key]
编辑:改为使用排序(d),而不是排序(运行起来也()),感谢Eli的!
实际上,您可以直接在“排序键(d):”中说“无需说”d.keys()“,因为迭代字典只是迭代其键。 – 2008-09-10 20:28:27
或更短,
for key, value in sorted(d.items()):
print value
不只是排序 - 避免查找 – 2008-09-10 20:13:08
>>> d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
>>> for k,v in sorted(d.items()):
... print v, k
...
this is a a
this is b b
this is c c
d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
ks = d.keys()
ks.sort()
for k in ks:
print "this is " + k
for key in sorted(d):
print d[key]
您也可以按值字典和控制排序顺序:
import operator
d = {'b' : 'this is 3', 'a': 'this is 2' , 'c' : 'this is 1'}
for key, value in sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True):
print key, " ", value
输出:
B本是3
a这是2
c这是1
你的意思是“排序”而不是“排序”?看起来你的问题旨在排序字典,而不是订购它。如果您的意思是“有序”,您可以使用集合模块中的OrderedDict。这些字典记得在输入了键/值对的顺序:
from collections import OrderedDict
参考信息:https://docs.python.org/2/library/collections.html#collections.OrderedDict
是的,但排序不提供老的Python(预2.4),所以这个成语仍是有用。 – jmanning2k 2008-09-10 21:03:37