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:25

Here is a solution which works both in Python 2 and Python 3:

dict((v, k) for k, v in list.items())[search_age]

The part until [search_age] constructs the reverse dictionary (where values are keys and vice-versa). You could create a helper method which will cache this reversed dictionary like so:

def find_name(age, _rev_lookup=dict((v, k) for k, v in ages_by_name.items())):
    return _rev_lookup[age]

or even more generally a factory which would create a by-age name lookup method for one or more of you lists

def create_name_finder(ages_by_name):
    names_by_age = dict((v, k) for k, v in ages_by_name.items())
    def find_name(age):
      return names_by_age[age]

so you would be able to do:

find_teen_by_age = create_name_finder({'george':16,'amber':19})
...
find_teen_by_age(search_age)

Note that I renamed list to ages_by_name since the former is a predefined type.

查看更多
情到深处是孤独
3楼-- · 2018-12-31 03:27

Sometimes int() may be needed:

titleDic = {'Фильмы':1, 'Музыка':2}

def categoryTitleForNumber(self, num):
    search_title = ''
    for title, titleNum in self.titleDic.items():
        if int(titleNum) == int(num):
            search_title = title
    return search_title
查看更多
弹指情弦暗扣
4楼-- · 2018-12-31 03:29
lKey = [key for key, value in lDictionary.iteritems() if value == lValue][0]
查看更多
闭嘴吧你
5楼-- · 2018-12-31 03:29

Here, recover_key takes dictionary and value to find in dictionary. We then loop over the keys in dictionary and make a comparison with that of value and return that particular key.

def recover_key(dicty,value):
    for a_key in dicty.keys():
        if (dicty[a_key] == value):
            return a_key
查看更多
谁念西风独自凉
6楼-- · 2018-12-31 03:30
def get_Value(dic,value):
    for name in dic:
        if dic[name] == value:
            del dic[name]
            return name
查看更多
听够珍惜
7楼-- · 2018-12-31 03:30

I found this answer very effective but still no very easy to read for me.

To make it more clear you can invert the key and the value of a dictionary. This is make the keys values and the values keys, as seen here.

mydict = {'george':16,'amber':19}
res = dict((v,k) for k,v in mydict.iteritems())
print(res[16]) # Prints george

or

mydict = {'george':16,'amber':19}
dict((v,k) for k,v in mydict.iteritems())[16]

which is essentially the same that this other answer.

查看更多
登录 后发表回答