[英]Sort python dictionary with list as value
I have a dictionary with list of values:-我有一本包含值列表的字典:-
dict_test = {
'TYPE' : [ 'S1', 'S2', 'S3', 'S4', 'S5' ],
'MARK' : [ 8, 11, 5, 34, 2 ]
}
I am trying to sort by key: MARK
我正在尝试按键排序: MARK
I got below approach from one of the previous post:-我从上一篇文章中得到了以下方法:-
>>> dict((k,sorted(v)) for k, v in dict_test.items())
{'TYPE': ['S1', 'S2', 'S3', 'S4', 'S5'], 'MARK': [2, 5, 8, 11, 34]}
But I noticed that this approach sorted the key: MARK
values, but it didn't sort the key: TYPE
value accordingly.但是我注意到这种方法对 key: MARK
值进行了排序,但没有对 key: TYPE
值进行相应的排序。
Eg TYPE: S1
is mapped to MARK: 8
initially.例如TYPE: S1
最初映射到MARK: 8
。 But after sort, TYPE: S1
is mapped to MARK: 2
但排序后, TYPE: S1
映射到MARK: 2
So what should I do to make sure if I sort key: MARK
it will adjust the order of key: TYPE
values as well?那么我应该怎么做才能确保我排序 key: MARK
它也会调整 key: TYPE
值的顺序?
Create a sorted list of (MARK, TYPE)
pairs.创建(MARK, TYPE)
对的排序列表。 Then update your dictionary:然后更新你的字典:
z = sorted(zip(dict_test['MARK'], dict_test['TYPE']))
dict_test['TYPE'] = [tup[1] for tup in z]
dict_test['MARK'] = [tup[0] for tup in z]
You need an extra function to get sorted index first and then apply it to your values of dict.您需要一个额外的 function 先获取排序索引,然后将其应用于您的 dict 值。
For instance:例如:
# Sort MARK
idxes = sorted(range(len(dict_test['MARK'])), key=lambda i: dict_test['MARK'][i])
dict_test['TYPE'] = [dict_test['TYPE'][i] for i in idxes]
dict_test['MARK'] = [dict_test['MARK'][i] for i in idxes]
Not the most pythonic approach but this should do the trick.不是最pythonic的方法,但这应该可以解决问题。
diction = {mark: type for mark, type in zip(dict_test['MARK'], dict_test['TYPE'])}
sorted_dict_test = {'TYPE': [], 'MARK': []}
for i in sorted(diction.items()):
sorted_dict_test['MARK'].append(i[0])
sorted_dict_test['TYPE'].append(i[1])
For python 3.7+:对于 python 3.7+:
Please note that since the diction
dictionary is built using int
keys, it is already sorted ascending and we do not need to use sorted(diction.items())
.请注意,由于字典是使用int
键构建的,因此它已经按升序排序,我们不需要使用sorted(diction.items())
diction
We can simply loop over the dictionary and build the sorted_dict_test
我们可以简单地遍历字典并构建sorted_dict_test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.