user20408 user20408 - 4 years ago 108
Python Question

finding the associated value in a list of lists

I have a list of lists that looks like this:
[['A', 35], ['B', 74], ['C', 21], ['D', 2]]

I want to find the first part of the list based on the second part.

For example, I know I want to get 'C' just by using 21. I know the second part (21) and want to use it to get the first part ('C'). What's the best way to do this?

Answer Source

You should use a dictionary for this:

newdic = dict((y,x) for x,y in mylist)