Get key by value in dictionary

后端 未结 30 2418
北恋
北恋 2020-11-21 06:28

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

dictionary = {\'george\' : 16, \'amber\' : 19}
search_age          


        
30条回答
  •  青春惊慌失措
    2020-11-21 07:19

    You need to use a dictionary and reverse of that dictionary. It means you need another data structure. If you are in python 3, use enum module but if you are using python 2.7 use enum34 which is back ported for python 2.

    Example:

    from enum import Enum
    
    class Color(Enum): 
        red = 1 
        green = 2 
        blue = 3
    
    >>> print(Color.red) 
    Color.red
    
    >>> print(repr(Color.red)) 
     
    
    >>> type(Color.red) 
     
    >>> isinstance(Color.green, Color) 
    True 
    
    >>> member = Color.red 
    >>> member.name 
    'red' 
    >>> member.value 
    1 
    

提交回复
热议问题