sherin_a27
sherin_a27

Reputation: 323

Comparing a dictionary value with a list and returning keys in list's order in Python

I have a dictionary like this:

dictionary = {'meeting': 311, 'dinner': 451, 'tonight': 572, 'telling': 992, 'one.': 1000}

and a list like this:

top_indices = [311, 992, 451]

I want to compare the dictionary with the list and return the keys of the dictionary. I'm able to do that using this code:

[keys for keys, indices in dictionary.items() if indices in top_indices]

This is giving me the result

['meeting',  'dinner', 'telling']

But I want the original order of the list to be unchanged, like this:

['meeting', 'telling',  'dinner']

How can I do that?

Upvotes: 1

Views: 687

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114230

You should invert the dictionary:

inverse = {index: key for key, index in dictionary.items()}

Now you can look up the keys in the correct order:

[inverse[index] for index in top_indices]

Another way would be

list(map(inverse.__getitem__, top_indices))

Upvotes: 1

CozyCode
CozyCode

Reputation: 504

If you swap the keys and the values it would be very easy. Try this:

dictionary = {311:'meeting', 451: 'dinner', 572:'tonight', 992:'telling', 1000:'one.'}
top_indices = [311, 992, 451]
x = []
for i in top_indices:
    x.append(dictionary.get(i))

Upvotes: 0

Related Questions