关于python:基于列表对字典的值进行排序

Sorting values of a dictionary based on a list

本问题已经有最佳答案,请猛点这里访问。

我想基于其中一个列表对字典(即列表)的值进行排序。例如,假设我有字典:

1
data = {'AttrA':[2,4,1,3],'AttrB':[12,43,23,25],'AttrC':['a','d','f','z']}

我想根据与ATTRA相关的值对其进行排序,这样:

1
data = {'AttrA':[1,2,3,4],'AttrB':[23,12,25,43],'AttrC':['f','a','z','d']}

提前谢谢!


根据data['AttrA']源列表,使用sorted()zip()对字典中的每个值进行排序,全部只使用3行代码:

1
2
3
base = data['AttrA'] # keep a reference to the original sort order
for key in data:
    data[key] = [x for (y,x) in sorted(zip(base, data[key]))]

演示:

1
2
3
4
5
6
7
>>> data = {'AttrA': [2, 4, 1, 3], 'AttrB': [12, 43, 23, 25], 'AttrC': ['a', 'd', 'f', 'z']}
>>> base = data['AttrA']
>>> for key in data:
...     data[key] = [x for (y,x) in sorted(zip(base, data[key]))]
...
>>> data
{'AttrB': [23, 12, 25, 43], 'AttrC': ['f', 'a', 'z', 'd'], 'AttrA': [1, 2, 3, 4]}


1
2
3
4
5
from operator import itemgetter
data = {'AttrA':[2,4,1,3],'AttrB':[12,43,23,25],'AttrC':['a','d','f','z']}

sort = itemgetter(*[i for i, v in sorted(enumerate(data['AttrA']), key=itemgetter(1))])
data = dict((k, list(sort(v))) for k, v in data.items())

或者一种较短但效率较低的创建sort的方法:

1
sort = itemgetter(*[data['AttrA'].index(v) for v in sorted(data['AttrA'])])

结果:

1
2
>>> data
{'AttrB': [23, 12, 25, 43], 'AttrC': ['f', 'a', 'z', 'd'], 'AttrA': [1, 2, 3, 4]}

它使用operator.itemgetter创建一个排序函数,按照data['AttrA']确定的顺序从序列中获取项目,然后将该排序函数应用于字典中的每个值。


未经测试,但应该工作(或者至少是一个好的开始的地方)

1
2
3
4
5
data = {'AttrA':[2,4,1,3],'AttrB':[12,43,23,25],'AttrC':['a','d','f','z']}
sortkey = 'AttrA'
sortedval = sorted(data['AttrA'])
valmaps = {i:sortedvals.find(num) for i,num in enumerate(data['AttrA'])}
newData = {k:[v[valmaps[i]] for i,_num in enumerate(v)] for k,v in data.items()}

希望这有帮助