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["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
:
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.
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. You can do this with the above snippet, but removing the line before printing which reconstructs diction