根据子字典中的值对字典进行排序

2024-06-28 00:16:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典如下

{"SPORTS": {"data": [["Bball", "10", 3]], "columns": ["SPORT", "MATCHES", "WINS"]}, "GRAMMY": {"data": [["Billy Joel", "Rock", 1], ["Elton John", "FUnk", 2]], "columns": ["ARTIST", "GENRE", "ID"]}, "SONGS": {"data": [], "columns": ["NAME", "ARTIST", "SONG_ID"]}}

我想按“数据”列表的大小对这本词典进行排序。换言之,以上我想排序为

{"GRAMMY": {"data": [["Billy Joel", "Rock", 1], ["Elton John", "FUnk", 2]], "columns": ["ARTIST", "GENRE", "ID"]},"SPORTS": {"data": [["Bball", "10", 3]], "columns": ["SPORT", "MATCHES", "WINS"]}, "SONGS": {"data": [], "columns": ["NAME", "ARTIST", "SONG_ID"]}
}

其中格莱美表有两行,体育表有一行,歌曲没有


Tags: columnsiddataartistjohnmatchesrockjoel
2条回答

如果您不介意创建一个新字典,您可以对键值对列表进行排序,然后将它们添加到OrderedDict(在collections库中),它会记住插入顺序。然后可以按照您想要的顺序将其作为JSON对象转储。你知道吗

d = {"SPORTS": {"data": [["Bball", "10", 3]], "columns": ["SPORT", "MATCHES", "WINS"]}, "GRAMMY": {"data": [["Billy Joel", "Rock", 1], ["Elton John", "FUnk", 2]], "columns": ["ARTIST", "GENRE", "ID"]}, "SONGS": {"data": [], "columns": ["NAME", "ARTIST", "SONG_ID"]}}
newd = OrderedDict(sorted(d.iteritems(), key=lambda x: len(x[1]['data']), reverse=True))
# change iteritems to items if python 3
# newd holds the sorted dictionaries

如果您可以使用JSON列表而不是对象,那么只需删除OrderedDict构造函数。你知道吗

您可以使用^{}来执行此操作。你知道吗

Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.

因此,解决方案是将原始dict转换成一个键值对列表,对其排序,然后从结果列表中构造一个OrderedDict。你知道吗

>>> d = {"SPORTS": {"data": [["Bball", "10", 3]], "columns": ["SPORT", "MATCHES", "WINS"]}, "GRAMMY": {"data": [["Billy Joel", "Rock", 1], ["Elton John", "FUnk", 2]], "columns": ["ARTIST", "GENRE", "ID"]}, "SONGS": {"data": [], "columns": ["NAME", "ARTIST", "SONG_ID"]}}
>>> from collections import OrderedDict
>>> OrderedDict(sorted(d.items(), key=lambda (k, v): len(v["data"]), reverse=True))OrderedDict([('GRAMMY', {'data': [['Billy Joel', 'Rock', 1], ['Elton John', 'FUnk', 2]], 'columns': ['ARTIST', 'GENRE', 'ID']}), ('SPORTS', {'data': [['Bball', '10', 3]], 'columns': ['SPORT', 'MATCHES', 'WINS']}), ('SONGS', {'data': [], 'columns': ['NAME', 'ARTIST', 'SONG_ID']})])
OrderedDict([('GRAMMY', {'data': [['Billy Joel', 'Rock', 1], ['Elton John', 'FUnk', 2]], 'columns': ['ARTIST', 'GENRE', 'ID']}), ('SPORTS', {'data': [['Bball', '10', 3]], 'columns': ['SPORT', 'MATCHES', 'WINS']}), ('SONGS', {'data': [], 'columns': ['NAME', 'ARTIST', 'SONG_ID']})])

相关问题 更多 >