Reputation: 27
Say I have a dictionary and some of the keys are values in a separate array, how do I sort the values in my array by the values for their respective keys in the dictionary?
For example:
input:
dict = {'a': 4, 'b': 7, 'c': 10, 'd': 1}
array = [a, b, d]
output:
array = ['d', 'a', 'b']
The order of the values in the output array would be "d" first because its value in the dictionary was the lowest (1). Followed by "a" (4) and "b" (7). I purposely did not include "c" in the array.
I am not asking for to solve this algorithmically
I am asking if there is a simple built-in way to do this, such as by using sorted(array, key= )
type function.
Upvotes: 0
Views: 36
Reputation: 4387
You can try this: dict = {'a': 4, 'b': 7, 'c': 10, 'd': 1} array = ["a", "b", "d"]
new_dict = sorted(dict.items(), key=lambda x: x[1])
output_array = []
for key, value in new_dict:
check_values = key in array
if(check_values == True):
output_array.append(key)
print(output_array)`
Upvotes: 0
Reputation:
Yes, you can use a lambda function that returns the value of a corresponding element in your dictionary.
By the way, I think it's not a good practice to use the word 'dict' for variable names as it is a built-in word in python.
print(sorted(array, key=lambda x: a_dict[x]))
Upvotes: 0
Reputation: 362557
What I think you're asking for:
>>> d = {'a': 4, 'b': 7, 'c': 10, 'd': 1}
>>> a = ['a', 'b', 'd']
>>> sorted(a, key=d.get)
['d', 'a', 'b']
Upvotes: 2