python字典根据值降序排序

标签 python dictionary

我想根据子键 key3 的值按降序对字典 d 进行排序。见下文:

d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
    }

所以最终的字典应该是这样的。

d = { '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
    }

我的方法是从 d 形成另一个字典 e,其键是 key3 的值,然后使用 reversed(sorted(e)) 但由于 key3 的值可以相同,所以字典 e 丢失了一些键及其值(value)观。有道理吗?

我怎样才能做到这一点?这不是经过测试的代码。我只是想理解其中的逻辑。

最佳答案

Dictionaries do not have any inherent order .或者更确切地说,它们的固有顺序是“任意而不是随机的”,所以对你没有任何好处。

在不同的术语中,您的 d 和您的 e 将是完全相同的字典。

您可以在此处使用 OrderedDict :

from collections import OrderedDict
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
    }
d_ascending = OrderedDict(sorted(d.items(), key=lambda kv: kv[1]['key3']))
d_descending = OrderedDict(sorted(d.items(), 
                                  key=lambda kv: kv[1]['key3'], reverse=True))

原来的d有一些任意的顺序。 d_ascending 具有您在原始 d认为的顺序,但没有。并且 d_descending 具有您想要的 e 顺序。


如果您真的不需要将 e 用作字典,但您只是希望能够以特定顺序迭代 d 的元素,你可以简化一下:

for key, value in sorted(d.items(), key=lambda kv: kv[1]['key3'], reverse=True):
    do_something_with(key, value)

如果您想在任何更改中按排序顺序维护字典,而不是 OrderedDict,则需要某种排序字典。您可以在 PyPI 上找到许多可用选项,其中一些在树上实现,另一些在 OrderedDict 之上实现,根据需要自行重新排序,等等。

关于python字典根据值降序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20577840/

相关文章:

c# - Ubuntu上的Unity/C#和Python通信

python - 在本地主机上运行时 python 导入错误

c# - 将 Dictionary<string, int> 转换为 Dictionary<int, List<string>>

python - 均匀生成不同整数的随机对

python - 使用 QThread 的正确方法是什么?

python - django-oauth2-提供者 : get the token without sending the client_secret

类内的Python多处理共享字典

iPhone 检查空字典

python - 从嵌套列表中获取不同的列表

arrays - 如何快速将字典分配给 AnyObject