List keys in a dictionary?

I have a dictionary

Dict = {'ALice':1, 'in':2, 'Wonderland':3} 

I could find ways to return key values, but there was no way to return key names.

I want Python to return dictionary key names step by step (for a loop), for example:

 Alice in Wonderland 
+7
source share
3 answers

You can use .keys() :

 for key in your_dict.keys(): print key 

or just iterate over the dictionary:

 for key in your_dict: print key 

Please note that the dictionaries are not ordered. The keys you received will come out in a somewhat random order:

 ['Wonderland', 'ALice', 'in'] 

If you care about the order, the solution will be to use lists that are ordered:

 sort_of_dict = [('ALice', 1), ('in', 2), ('Wonderland', 3)] for key, value in sort_of_dict: print key 

Now you will get the desired results:

 >>> sort_of_dict = [('ALice', 1), ('in', 2), ('Wonderland', 3)] >>> >>> for key, value in sort_of_dict: ... print key ... ALice in Wonderland 
+13
source

dict has a keys () method.

Dict.keys () will return a list of keys or use the iterator iterkeys () method.

+1
source
 def enumdict(listed): myDict = {} for i, x in enumerate(listed): myDict[x] = i return myDict indexes = ['alpha', 'beta', 'zeta'] print enumdict(indexes) 

prints: {'alpha': 0, 'beta': 1, 'zeta': 2}

Edit: if you want the dict to be ordered, use orderdict.

+1
source

All Articles