How can I get dictionary key as variable directly in Python (not by searching from value)?
Solution 1:
You should iterate over keys with:
for key in mydictionary:
print "key: %s , value: %s" % (key, mydictionary[key])
Solution 2:
If you want to access both the key and value, use the following:
Python 2:
for key, value in my_dict.iteritems():
print(key, value)
Python 3:
for key, value in my_dict.items():
print(key, value)
Solution 3:
The reason for this is that I am printing these out to a document and I want to use the key name and the value in doing this
Based on the above requirement this is what I would suggest:
keys = mydictionary.keys()
keys.sort()
for each in keys:
print "%s: %s" % (each, mydictionary.get(each))