我想根据其中一个列表对字典(列表)的值进行排序。例如,说我有字典:
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']}
提前谢谢!
答案 0 :(得分:6)
根据data['AttrA']
来源列表,使用sorted()
和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]}
答案 1 :(得分: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']
确定的顺序从序列中获取项目,然后将该排序函数应用于字典中的每个值。
答案 2 :(得分: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()}
希望这有帮助