How to print a dictionary's key?

前端 未结 20 726
眼角桃花
眼角桃花 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: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.
    
    0 讨论(0)
  • 2020-11-27 09:50
    key_name = '...'
    print "the key name is %s and its value is %s"%(key_name, mydic[key_name])
    
    0 讨论(0)
  • 2020-11-27 09:54

    Make sure to do

    dictionary.keys()
    # rather than
    dictionary.keys
    
    0 讨论(0)
  • 2020-11-27 09:55

    Try this:

    def name_the_key(dict, key):
        return key, dict[key]
    
    mydict = {'key1':1, 'key2':2, 'key3':3}
    
    key_name, value = name_the_key(mydict, 'key2')
    print 'KEY NAME: %s' % key_name
    print 'KEY VALUE: %s' % value
    
    0 讨论(0)
  • 2020-11-27 09:57
    dic = {"key 1":"value 1","key b":"value b"}
    
    #print the keys:
    for key in dic:
        print key
    
    #print the values:
    for value in dic.itervalues():
        print value
    
    #print key and values
    for key, value in dic.iteritems():
        print key, value
    

    Note:In Python 3, dic.iteritems() was renamed as dic.items()

    0 讨论(0)
  • 2020-11-27 09:57

    To access the data, you'll need to do this:

    foo = {
        "foo0": "bar0",
        "foo1": "bar1",
        "foo2": "bar2",
        "foo3": "bar3"
    }
    for bar in foo:
      print(bar)
    

    Or, to access the value you just call it from the key: foo[bar]

    0 讨论(0)
提交回复
热议问题