How to print a dictionary's key?

前端 未结 20 861
眼角桃花
眼角桃花 2020-11-27 09:22

I would like to print a specific Python dictionary key:

mydic = {}
mydic[\'key_name\'] = \'value_name\'

Now I can check if mydic.has_

20条回答
  •  青春惊慌失措
    2020-11-27 09:37

    If you want to get the key of a single value, the following would help:

    def get_key(b): # the value is passed to the function
        for k, v in mydic.items():
            if v.lower() == b.lower():
                return k
    

    In pythonic way:

    c = next((x for x, y in mydic.items() if y.lower() == b.lower()), \
         "Enter a valid 'Value'")
    print(c)
    

提交回复
热议问题