一种像这样的数据结构。
什么是在顶层字典的值内按
{
'ford': {'count': 3},
'mazda': {'count': 0},
'toyota': {'count': 1}
}
什么是在顶层字典的值内按
count
值排序的最佳方法?{
'ford': {'count': 3},
'mazda': {'count': 0},
'toyota': {'count': 1}
}
count
值排序的最佳方法?d = {'ford': {'count': 3},
'mazda': {'count': 0},
'toyota': {'count': 1}}
>>> sorted(d.items(), key=lambda (k, v): v['count'])
[('mazda', {'count': 0}), ('toyota', {'count': 1}), ('ford', {'count': 3})]
为了保持结果为字典,可以使用collections.OrderedDict
:>>> from collections import OrderedDict
>>> ordered = OrderedDict(sorted(d.items(), key=lambda (k, v): v['count']))
>>> ordered
OrderedDict([('mazda', {'count': 0}), ('toyota', {'count': 1}), ('ford', {'count': 3})])
>>> ordered.keys() # this is guaranteed to come back in the sorted order
['mazda', 'toyota', 'ford']
>>> ordered['mazda'] # still a dictionary
{'count': 0}
版本相关:
d.iteritems()
替代 d.items()
来获得更好的内存效率。collections.OrderedDict
只在 Python 2.7 和 Python 3.2(及以上版本)中可用。字典是一种无序的数据结构,因此不能进行排序。您可以从字典 d
创建一个已排序的列表(或在 Python 2.7 中使用 OrderedDict
):
sorted(d.iteritems(), key=lambda item: item[1]["count"])
这个列表可以作为 collections.OrderedDict
的构造函数参数。
>>> from operator import itemgetter
>>> sorted(s,key=itemgetter,reverse=True)
['ford', 'toyota', 'mazda']
>>> collections.OrderedDict(sorted(d.iteritems(),key=lambda x:x[1]["count"],reverse=True))
OrderedDict([('ford', {'count': 3}), ('toyota', {'count': 1}), ('mazda', {'count': 0})])
>>>
我认为一个dict就是一个哈希表,因此实际上不能对其进行排序。尝试将已排序的值存储到列表中,这样可以排序:
l = []
for x in sorted(dictionary.keys()):
l.append([dictionary[x]])
collections.OrderedDict
。 - 0xc0de