Richard302
Richard302

Reputation: 11

Retrieve keys using values from a dictionary

Basically I am trying to find a way to get the key of a value from a dictionary by searching the value.

people = {
    "Sarah" : "36",
    "David" : "42",
    "Ricky" : "13"
    }


user_input = ('Enter the age of the individual") #The user enters the 
                                                 #value 
key_to_output = (...) #The variable that would contain the key value
print(key_to_output)

For example in the dictionary above if the user enters "36", they would be returned have "Sarah" returned. The dictionary I am using will never have a overlapping values so don't worry about any issues that would cause.

Also, because my python knowledge isn't very advanced it would be much appreciated if the responses were kept quite amateur so I can understand them properly.

Upvotes: 0

Views: 151

Answers (2)

pkapka
pkapka

Reputation: 5346

You can invert the dictionary as so -

people_inv = {v:k for k,v in people.items()}

Now say your user inputted 36,

user_input = "36"
people_inv[user_input] # this will give Sarah

If the values are not unique like in the example below, you can do this -

people = {"Sarah":36, "Ricky":36, "Pankaj":28} 
people_inv= {}
for k,v in people.items():
    people_inv.setdefault(v, []).append(k)
people_inv["36"]

Output

['Sarah', 'Ricky']

Upvotes: 2

NameVergessen
NameVergessen

Reputation: 643

The easyest way would be to itterate over the values like this.

    def find_key(value, people):
        for name in people:
            if people[name] == value:
                return name

If you are trying to get mutliple keys I would try:

   def find_key(value, people):
       names = []
       for name in people:
           if people[name] == value:
               names.append(name)
       return names

Upvotes: 1

Related Questions