-1

So let's say I have a dictionary:

my_dict = {'A' : 250, 'B' : 270, 'C' : 240}

And I have a list that has values sorted in descending order:

my_list = [270, 250, 240]

Now, I want to create a list that looks like this:

new_list = ['B', 'A', 'C']

The elements are ordered in accordance with my_list. How do I make this possible? Thanks.

Ryan Oh
  • 597
  • 5
  • 21
  • Best way I can think of is to create new dictionary with values and keys (as you might have duplicate values in current dictionary). Iterate through the dict and get the values which are the keys in old dictionary. – Underoos Jan 20 '21 at 05:10
  • 1
    Does this answer your question? [Get key by value in dictionary](https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary) – Mahan Lamee Jan 20 '21 at 05:23

6 Answers6

3

If you are allowed to assume that there are no duplicates in the dict values, then you could invert the dict:

my_dict = {'A' : 250, 'B' : 270, 'C' : 240}
my_list = [270, 250, 240]
inverse_dict = dict([(val, key) for key, val in my_dict.items()])
output = [inverse_dict[key] for key in my_list]

If duplicate values are allowed, of course, the question would have to be re-specified to define the behavior in case of a duplicate, to the assumption of no duplicate values seems reasonable.

Of course, this goes very much against the grain of the dict data structure, and one wonders why this data is coming to us as the wrong dict in the first place. A solution like this implies that some refactoring is required somewhere.

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
2
my_dict = {'A' : 250, 'B' : 270, 'C' : 240} 
my_list = [270, 250, 240]

def getKey(value):
  for key, val in my_dict.items():
    if (val == value):
      return key

answer = list(map(getKey, my_list))
print(answer)

If you just want to sort the dictionary, you don't need that extra list. You can just do this:

my_dict = {'A' : 250, 'B' : 270, 'C' : 240} 

ordered = dict(sorted(my_dict.items(), reverse=True, key=lambda item: item[1]))
answer = list(ordered.keys())
print(answer)
1

First, invert the dictionary using dictionary comprehension. Then use list comprehension to get the desired list:

inv_dict = {y: x for x, y in my_dict.items()}
new_list = [inv_dict[x] for x in my_list]
print(new_list)
# ['B', 'A', 'C']
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
1

I found the easiest way would be to use dictionary comprehension.

In one line:

new_list = list(dict(sorted({v:k for k, v in my_dict.items()}.items(), reverse=True)).values())

Since it gets a little messy, I'll break it down from inner to outer

  1. {v:k for k, v in my_dict.items()}: This part simply switches the keys and the values. So, in this case, from {'A' : 250, 'B' : 270, 'C' : 240} to {250: 'A', 270: 'B', 240: 'C'}
  2. sorted({v:k for k, v in my_dict.items()}.items(), reverse=True): This takes the altered dictionary sorts it by its keys. (Remember that the keys in this dictionary are the values of the original.) By passing reverse=True, the items are sorted in numerical descending order
  3. dict(sorted({v:k for k, v in my_dict.items()}.items(), reverse=True)): Using sorted() returns a list of tuples of key, value pairs. Use the dict() function to convert the pairs into a dictionary
  4. list(dict(sorted({v:k for k, v in my_dict.items()}.items(), reverse=True)).values()): Since we only want the values (the letters), use the values method. Pass that to list() to change the data from a dictValues type to a list type.
Jacob Lee
  • 4,405
  • 2
  • 16
  • 37
  • I would suggest using a few more lines and a few more names. If you need 12 lines of explanation, your one-liner is probably too short, particularly for pedagogical purposes. – Jon Kiparsky Jan 20 '21 at 19:32
0
my_dict = {'A' : 250, 'B' : 270, 'C' : 240}
my_list = [270, 250, 240]
answer = []
for num in my_list:
    for key, value in my_dict.items():
        if num == value:
            answer.append(key)
Armen Halajyan
  • 87
  • 1
  • 2
  • 9
0

It would be like this;

Code Syntax

my_dict = {'A' : 250, 'B' : 270, 'C' : 240}
my_list = [270, 250, 240]

def valKey(dict, list):
    return [key for val in list for key, value in dict.items() if val == value]


print(valKey(my_dict, my_list))

Output

['B', 'A', 'C']

[Program finished]
Ahmed
  • 796
  • 1
  • 5
  • 16