1

我想根据其中一个列表对字典(列表)的值进行排序。例如说我有字典:

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

我想根据与 AttrA 关联的值对其进行排序,例如:

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

先感谢您!

4

3 回答 3

6

根据data['AttrA']源列表,使用sorted()and对字典中的每个值进行排序zip(),只需 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]))]

演示:

>>> 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]}
于 2013-07-22T20:43:43.600 回答
1
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

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

结果:

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

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

于 2013-07-22T20:46:29.687 回答
0

未经测试,但应该可以工作(或者至少是一个很好的起点)

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()}

希望这可以帮助

于 2013-07-22T20:43:52.660 回答