如何在python字典中对字典进行排序
所以我被困了整整一个小时。我看过其他关于这个问题的帖子,但我不能让我的帖子起作用 这是我要整理的字典中的字典:如何在python字典中对字典进行排序,python,sorting,dictionary,lambda,ordereddictionary,Python,Sorting,Dictionary,Lambda,Ordereddictionary,所以我被困了整整一个小时。我看过其他关于这个问题的帖子,但我不能让我的帖子起作用 这是我要整理的字典中的字典: diction = {'z': {'golf': 3, 'bowling': 9}, 'a': {'fed': 5, 'alvin': 10}, 'r': {'yell': 7, 'shout': 11}} 我试图首先对字典的最外层进行排序,所以t[0]就是从这里来的。然后我想按字母顺序对与字母成对的元素进行排序。所需的输出-- 这是我的密码: import collections
diction = {'z': {'golf': 3, 'bowling': 9}, 'a': {'fed': 5, 'alvin': 10}, 'r': {'yell': 7, 'shout': 11}}
我试图首先对字典的最外层进行排序,所以t[0]就是从这里来的。然后我想按字母顺序对与字母成对的元素进行排序。所需的输出--
这是我的密码:
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}}
您有一个
dict
,其值为dict
s
将外部对象转换为OrderedDict
不会改变内部对象。你也必须改变它们
当然,你需要对它们进行分类;单个sorted
调用不能同时在两个级别上工作
因此:
您的内部词典没有排序,因此它们将无法维持其顺序:
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()))
你能描述一下“显而易见”的问题吗?
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]))
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()))