[英]Sort list of values in a dictionary
Let's say I have the following dictionary:假设我有以下字典:
diction = {"string": ["alabama", "fruit", "emoji"], "number": [9, 13, 20]}
How to obtain a dictionary where the values from "number" key are ordered descendingly and the "string" should be ordered as well as per the number key ordered?如何获得一个字典,其中“数字”键的值按降序排序,“字符串”应该按照排序的数字键排序? String and number key are linked
字符串和数字键链接
I want to get我想得到
diction = {"string": ["emoji", "fruit", "alabama"], "number": [20, 13, 9]}
I appreciate a lot.我很感激。
Use sorted by another list selected by diction['number']
:使用由
diction['number']
选择的另一个列表排序:
diction["string"] = [x for _,x in sorted(zip(diction['number'],
diction['string']),
key=lambda pair: pair[0],
reverse=True)]
diction["number"] = sorted(diction["number"], reverse=True)
print (diction)
{'string': ['emoji', 'fruit', 'alabama'], 'number': [20, 13, 9]}
Or use pandas
:或使用
pandas
:
import pandas as pd
d = pd.DataFrame(diction).sort_values('number', ascending=False).to_dict(orient='list')
print (d)
{'string': ['emoji', 'fruit', 'alabama'], 'number': [20, 13, 9]}
Here is a method to obtain your desired output.这是获得所需 output 的方法。
from collections import defaultdict
diction = {"string": ["alabama", "fruit", "emoji"], "number": [9, 13, 20]}
d = defaultdict(list)
for strng, num in zip(diction["string"], diction["number"]):
d[strng].append(num)
d = dict(sorted(d.items(), key=lambda x: x[1], reverse=True))
diction = {"string": [k for k in d.keys()], "number": [j[0] for j in d.values()]}
print(diction)
Outputs:输出:
{'string': ['emoji', 'fruit', 'alabama'], 'number': [20, 13, 9]}
I am in agreement with JeffUK 's comment about using key/value pairs.我同意JeffUK关于使用键/值对的评论。 You can do this with the above snippet, but removing the line before printing which reconstructs
diction
您可以使用上面的代码片段执行此操作,但在打印之前删除重建
diction
的行
sorted
will work fine. sorted
会正常工作。
diction["number"] = sorted(diction["number"])
For a generalized approach that will sort all lists in the dictionary based on the reordering of sorting one of them, you can build a list of indexes in the new sort order and apply it to all the lists:对于将基于排序其中一个的重新排序对字典中的所有列表进行排序的通用方法,您可以以新的排序顺序构建索引列表并将其应用于所有列表:
diction = {"string": ["alabama", "fruit", "emoji"], "number": [9, 13, 20]}
keys = diction["number"] # list to sort
order = sorted(range(len(keys)),key=lambda i:keys[i],reverse=True) # indexes
for lst in diction.values():
lst[:] = [lst[i] for i in order] # apply new order to all lists
print(diction)
{'string': ['emoji', 'fruit', 'alabama'], 'number': [20, 13, 9]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.