按值python排序dict

kin*_*auk 75 python dictionary python-2.6

假设我有一个字典.

data = {1:'b', 2:'a'}
Run Code Online (Sandbox Code Playgroud)

我希望按'b'和'a'对数据进行排序,以便得到结果

'a','b'
Run Code Online (Sandbox Code Playgroud)

我怎么做?
有任何想法吗?

Joh*_*ooy 158

要使用值

sorted(data.values())
Run Code Online (Sandbox Code Playgroud)

要获取匹配的键,请使用key函数

sorted(data, key=data.get)
Run Code Online (Sandbox Code Playgroud)

获取按值排序的元组列表

sorted(data.items(), key=lambda x:x[1])
Run Code Online (Sandbox Code Playgroud)

相关:请参阅此处的讨论:字典按Python 3.6+排序

  • 对于崇敬的顺序,排序(data.items(),key = lambda x:x [1],reverse = True) (2认同)

jam*_*lak 40

如果你真的想要对字典进行排序而不是仅仅获取排序列表使用 collections.OrderedDict

>>> from collections import OrderedDict
>>> from operator import itemgetter
>>> data = {1: 'b', 2: 'a'}
>>> d = OrderedDict(sorted(data.items(), key=itemgetter(1)))
>>> d
OrderedDict([(2, 'a'), (1, 'b')])
>>> d.values()
['a', 'b']
Run Code Online (Sandbox Code Playgroud)

  • @kingRauk然后不要标记你的问题Python 2.7 ....你在评论中提到的很多事情都应该在你的问题中开始 (6认同)

njz*_*zk2 17

从您的评论到gnibbler答案,我想说你想要一个按值排序的键值对列表:

sorted(data.items(), key=lambda x:x[1])
Run Code Online (Sandbox Code Playgroud)


kin*_*auk 8

谢谢你的所有答案.你是我的所有英雄;-)

到底是这样的:

d = sorted(data, key = d.get)

for id in d:
    text = data[id]
Run Code Online (Sandbox Code Playgroud)


Mor*_*lde 5

我还认为必须注意Python dict对象类型是一个哈希表(在此更多信息),因此如果不将其键/值转换为列表就无法进行排序。不管字典中元素的大小/数量如何,这都允许dict在恒定时间内进行项目检索O(1)

话虽如此,对键- sorted(data.keys())或值-进行排序后sorted(data.values()),就可以使用该列表访问设计模式中的键/值,例如:

for sortedKey in sorted(dictionary):
    print dictionary[sortedKeY] # gives the values sorted by key

for sortedValue in sorted(dictionary.values()):
    print sortedValue # gives the values sorted by value
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。

  • sorted(dictionary)优于sorted(dictionary.keys()) (3认同)

小智 5

您可以从值创建排序列表并重建字典:

myDictionary={"two":"2", "one":"1", "five":"5", "1four":"4"}

newDictionary={}

sortedList=sorted(myDictionary.values())

for sortedKey in sortedList:
    for key, value in myDictionary.items():
        if value==sortedKey:
            newDictionary[key]=value
Run Code Online (Sandbox Code Playgroud)

输出:newDictionary={'一':'1','二':'2','1four':'4','五':'5'}