Get key by value in dictionary

2018-12-31 02:46发布

I made a function which will look up ages in a Dictionary and show the matching name:

dictionary = {'george' : 16, 'amber' : 19}
search_age = raw_input("Provide age")
for age in dictionary.values():
    if age == search_age:
        name = dictionary[age]
        print name

I know how to compare and find the age I just don't know how to show the name of the person. Additionally, I am getting a KeyError because of line 5. I know it's not correct but I can't figure out how to make it search backwards.

30条回答
高级女魔头
2楼-- · 2018-12-31 03:31
get_key = lambda v, d: next(k for k in d if d[k] is v)
查看更多
皆成旧梦
3楼-- · 2018-12-31 03:33
mydict = {'george':16,'amber':19}
print mydict.keys()[mydict.values().index(16)] # Prints george

Or in Python 3.x:

mydict = {'george':16,'amber':19}
print(list(mydict.keys())[list(mydict.values()).index(16)]) # Prints george

Basically, it separates the dictionary's values in a list, finds the position of the value you have, and gets the key at that position.

More about keys() and .values() in Python 3: Python: simplest way to get list of values from dict?

查看更多
刘海飞了
4楼-- · 2018-12-31 03:33
a = {'a':1,'b':2,'c':3}
{v:k for k, v in a.items()}[1]

or better

{k:v for k, v in a.items() if v == 1}
查看更多
不流泪的眼
5楼-- · 2018-12-31 03:33

I hope this might help...

for key in list:
   if list[key] == search_value:
       return key
查看更多
妖精总统
6楼-- · 2018-12-31 03:34

There is none. dict is not intended to be used this way.

for name, age in dictionary.items():    # for name, age in dictionary.iteritems():  (for Python 2.x)
    if age == search_age:
        print(name)
查看更多
零度萤火
7楼-- · 2018-12-31 03:34

If you want both the name and the age, you should be using .items() which gives you key (key, value) tuples:

for name, age in mydict.items():
    if age == search_age:
        print name

You can unpack the tuple into two separate variables right in the for loop, then match the age.

You should also consider reversing the dictionary if you're generally going to be looking up by age, and no two people have the same age:

{16: 'george', 19: 'amber'}

so you can look up the name for an age by just doing

mydict[search_age]

I've been calling it mydict instead of list because list is the name of a built-in type, and you shouldn't use that name for anything else.

You can even get a list of all people with a given age in one line:

[name for name, age in mydict.items() if age == search_age]

or if there is only one person with each age:

next((name for name, age in mydict.items() if age == search_age), None)

which will just give you None if there isn't anyone with that age.

Finally, if the dict is long and you're on Python 2, you should consider using .iteritems() instead of .items() as Cat Plus Plus did in his answer, since it doesn't need to make a copy of the list.

查看更多
登录 后发表回答