How to print a dictionary's key?

前端 未结 20 859
眼角桃花
眼角桃花 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:48

    Since we're all trying to guess what "print a key name" might mean, I'll take a stab at it. Perhaps you want a function that takes a value from the dictionary and finds the corresponding key? A reverse lookup?

    def key_for_value(d, value):
        """Return a key in `d` having a value of `value`."""
        for k, v in d.iteritems():
            if v == value:
                return k
    

    Note that many keys could have the same value, so this function will return some key having the value, perhaps not the one you intended.

    If you need to do this frequently, it would make sense to construct the reverse dictionary:

    d_rev = dict(v,k for k,v in d.iteritems())
    

提交回复
热议问题