I would like to print a specific Python dictionary key:
mydic = {}
mydic[\'key_name\'] = \'value_name\'
Now I can check if mydic.has_
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.
key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])
Make sure to do
dictionary.keys()
# rather than
dictionary.keys
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
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()
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]