Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Iterate Dictionary by Index

I want to iterate through a dictionary in python by index number.

Example :

 dict = {'apple':'red','mango':'green','orange':'orange'} 

I want to iterate through the dictionary from first to last, so that I can access the dictionary items by their indexes. For example, the 1st item will be apple, and the 2nd item will be mango and value will be green.

Something like this:

for i in range(0,len(dict)):     dict.i 
like image 822
Dev.K. Avatar asked Jul 22 '13 17:07

Dev.K.


People also ask

How do you iterate over an index in a dictionary?

Iterate over all key-value pairs of dictionary by index As we passed the sequence returned by items() to the enumerate() function with start index 0 (default value). Therefore it yielded each item (key-value) of dictionary along with index, starting from 0.

Can you index dictionaries in Python?

You can find a dict index by counting into the dict. keys() with a loop. If you use the enumerate() function, it will generate the index values automatically.


2 Answers

You can iterate over keys and get values by keys:

for key in dict.iterkeys():     print key, dict[key] 

You can iterate over keys and corresponding values:

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

You can use enumerate if you want indexes (remember that dictionaries don't have an order):

>>> for index, key in enumerate(dict): ...     print index, key ...  0 orange 1 mango 2 apple >>>  
like image 108
alecxe Avatar answered Sep 18 '22 23:09

alecxe


There are some very good answers here. I'd like to add the following here as well:

some_dict = {     "foo": "bar",     "lorem": "ipsum" }  for index, (key, value) in enumerate(some_dict.items()):     print(index, key, value) 

results in

0 foo bar 1 lorem ipsum 

Appears to work with Python 2.7 and 3.5

like image 36
Serguei Fedorov Avatar answered Sep 20 '22 23:09

Serguei Fedorov