Reputation: 129
I have a dictionary of lists of the form:
dict1 = { key1 : ['a', 'b'], key2: ['c', 'd'], key3: ['e']}
I have another dictionary which is of the form
dict2 = { a: 10, b: 11, c: 6, d: 15, e: 3}
I want to sort dict1 in reverse order based on values of dict 2, so the result would be something like:
sorted_dict = { key2:['d', 'c'], key1: ['b', 'a'], key3:['e']}
Edit: I need to preserve the order of keys. I could convert this as a tuple as well, which is perfectly acceptable.
Thank you!
Upvotes: 0
Views: 95
Reputation: 6234
To sort the dictionary values you can do:
sorted_dict = {
key: sorted(value, key=lambda x: dict2.get(x, 0), reverse=True)
for key, value in dict1.items()
}
Then to sort the dictionary(change the order of keys) you can do:
sorted_dict = dict(
sorted(
sorted_dict.items(),
key=lambda x: sum(dict2.get(i, 0) for i in x[1]),
reverse=True,
)
)
A side note on the order of keys in dictionary.
Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
Upvotes: 1
Reputation: 1258
You cannot sort a dictionary but you can sort a list. I suggest a similar approach to what I've done below that would sort the keys after mapping the values from dict2 then creates a new unordered
dictionary from the sorted keys.
dict1 = { "key1" : ['a', 'b'], "key2": ['c', 'd'], "key3": ['e']}
dict2 = { "a": 10, "b": 11, "c": 6, "d": 15, "e": 3}
sorted_keys = sorted([key for key in dict1], key=lambda x: sum([dict2[el] for el in dict1[x]]), reverse=True)
sorted_dict = {k: dict1[k] for k in sorted_keys}
This produces
{'key1': ['b', 'a'], 'key2': ['d', 'c'], 'key3': ['e']}
sorted by the mapped value
Upvotes: 0
Reputation: 9018
You can use the key
argument in sorted
:
sorted_dict = {}
for k in dict1:
sorted_dict[k] = sorted(dict1[k], key=lambda v: dict2[v], reverse=True)
This gives:
{'key1': ['b', 'a'], 'key2': ['d', 'c'], 'key3': ['e']}
Upvotes: 1