【问题标题】:how to sort dictionary within a dictionary python如何在字典python中对字典进行排序
【发布时间】:2014-11-10 21:57:11
【问题描述】:

所以我现在已经被困了整整一个小时。我看过其他关于同一问题的帖子,但我无法让我的工作。

这是我要排序的字典中的字典:

diction = {'z': {'golf': 3, 'bowling': 9}, 'a': {'fed': 5, 'alvin': 10}, 'r': {'yell': 7, 'shout': 11}}

我试图首先对字典的最外层进行排序,这就是 t[0] 出现的地方。然后我想按字母顺序对与字母配对的元素进行排序。想要的输出——

{a:{alvin:10, fed:5}, r:{shout:11, yell:7}, z:{bowling:9, golf:3}}

这是我的代码:

import collections
diction = {'z': {'golf': 3, 'bowling': 9}, 'a': {'fed': 5, 'alvin': 10}, 'r': {'yell': 7, 'shout': 11}}
a= collections.OrderedDict(sorted(diction.items(),key=lambda  t:t[0][1]))

这显然行不通。

编辑

所以到目前为止,这只是按字母排序。我得到:

{a: {fed:5, alvin:10}, r:{yell:7, shout:11}, z:{golf:3, bowling:9}}

我希望它显示什么:

{a:{alvin:10, fed:5}, r:{shout:11, yell:7}, z:{bowling:9, golf:3}}

【问题讨论】:

  • 你能描述一下“明显”的问题吗?

标签: python sorting dictionary lambda ordereddictionary


【解决方案1】:

你的内部字典不是OrderedDict,所以它们不会保持它们的顺序:

from collections import OrderedDict
diction ={'z': {'golf': 3, 'bowling': 9}, 'a': {'fed': 5, 'alvin': 10}, 'r': {'yell': 7, 'shout': 11}}
a = OrderedDict(sorted(diction.items()))
for key, subdict in a.items():
    a[key] = OrderedDict(sorted(subdict.items()))

【讨论】:

    【解决方案2】:

    您有一个dict,其值为dicts。

    将外部对象转换为OrderedDict 不会更改内部对象。你也必须改变它们。

    当然,您需要对它们中的每一个进行排序;单个sorted 调用不能同时在两个级别上工作。

    所以:

    sorted_items = ((innerkey, sorted(innerdict.items(), key=lambda t: t[0]))
                    for innerkey, innerdict in diction.items())
    a = collections.OrderedDict(sorted(sorted_items, key=lambda t: t[0]))
    

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 2021-04-17
      • 2016-06-08
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      相关资源
      最近更新 更多