Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a dictionary's key?

People also ask

How do I print a key?

However, you can use the keyboard shortcut key Ctrl + P to open the print window on a PC or Command + P to open the print window on an Apple computer.

How do I print a dictionary value?

To print dictionary items: key:value pairs, keys, or values, you can use an iterator for the corresponding key:value pairs, keys, or values, using dict. items(), dict. keys(), or dict. values() respectively and call print() function.


A dictionary has, by definition, an arbitrary number of keys. There is no "the key". You have the keys() method, which gives you a python list of all the keys, and you have the iteritems() method, which returns key-value pairs, so

for key, value in mydic.iteritems() :
    print key, value

Python 3 version:

for key, value in mydic.items() :
    print (key, value)

So you have a handle on the keys, but they only really mean sense if coupled to a value. I hope I have understood your question.


Additionally you can use....

print(dictionary.items()) #prints keys and values
print(dictionary.keys()) #prints keys
print(dictionary.values()) #prints values

Hmm, I think that what you might be wanting to do is print all the keys in the dictionary and their respective values?

If so you want the following:

for key in mydic:
  print "the key name is" + key + "and its value is" + mydic[key]

Make sure you use +'s instead of ,' as well. The comma will put each of those items on a separate line I think, where as plus will put them on the same line.


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()