Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerate 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 the dictionary key names step by step (for loop) for example:

Alice
in
Wonderland
like image 852
upapilot Avatar asked Apr 10 '12 05:04

upapilot


People also ask

How do you enumerate a dictionary key?

To enumerate both keys and values, we can use the dictionary items() method. The items() method returns an object with the key-value pairs as tuples. The following example shows how we can use the items() method with the enumerate() function and access both the key and its corresponding value.

Can you use enumerate on a dictionary Python?

Python allows you to enumerate both keys and values of a dictionary.

What are the keys in a dictionary?

Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

How do I print a list of the keys in a dictionary?

To print the dictionary keys in Python, use the dict. keys() method to get the keys and then use the print() function to print those keys. The dict. keys() method returns a view object that displays a list of all the keys in the dictionary.


1 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

Do note that dictionaries aren't ordered. Your resulting keys will come out in a somewhat random order:

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

If you care about order, a solution would be to use lists, which are ordered:

sort_of_dict = [('ALice', 1), ('in', 2), ('Wonderland', 3)]

for key, value in sort_of_dict:
  print key

Now you get your desired results:

>>> sort_of_dict = [('ALice', 1), ('in', 2), ('Wonderland', 3)]
>>> 
>>> for key, value in sort_of_dict:
...   print key
... 
ALice
in
Wonderland
like image 157
Blender Avatar answered Sep 17 '22 12:09

Blender