How to print a dictionary's key?

前端 未结 20 863
眼角桃花
眼角桃花 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条回答
  •  旧时难觅i
    2020-11-27 09:49

    I looked up this question, because I wanted to know how to retrieve the name of "the key" if my dictionary only had one entry. In my case, the key was unknown to me and could be any number of things. Here is what I came up with:

    dict1 = {'random_word': [1,2,3]}
    key_name = str([key for key in dict1]).strip("'[]'")        
    print(key_name)  # equal to 'random_word', type: string.
    

提交回复
热议问题