简体   繁体   中英

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

sorted will work fine.

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]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM