[python] 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

This question is related to python dictionary

The answer is


When I need to keep the order, I use a list and a companion dict:

color = ['red','green','orange']
fruit = {'apple':0,'mango':1,'orange':2}
color[fruit['apple']]
for i in range(0,len(fruit)): # or len(color)
    color[i]

The inconvenience is I don't get easily the fruit from the index. When I need it, I use a tuple:

fruitcolor = [('apple','red'),('mango','green'),('orange','orange')]
index = {'apple':0,'mango':1,'orange':2}
fruitcolor[index['apple']][1]
for i in range(0,len(fruitcolor)): 
    fruitcolor[i][1]
for f, c in fruitcolor:
    c

Your data structures should be designed to fit your algorithm needs, so that it remains clean, readable and elegant.


I wanted to know (idx, key, value) for a python OrderedDict today (mapping of SKUs to quantities in order of the way they should appear on a receipt). The answers here were all bummers.

In python 3, at least, this way works and and makes sense.

In [1]: from collections import OrderedDict
   ...: od = OrderedDict()
   ...: od['a']='spam'
   ...: od['b']='ham'
   ...: od['c']='eggs'
   ...: 
   ...: for i,(k,v) in enumerate(od.items()):
   ...:    print('%d,%s,%s'%(i,k,v))
   ...: 
0,a,spam
1,b,ham
2,c,eggs

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

Do this:

for i in dict.keys():
  dict[i]

There are several ways to call the for-loop in python and here what I found so far:

A = [1,2,3,4]
B = {"col1": [1,2,3],"col2":[4,5,6]}

# Forms of for loop in python:
# Forms with a list-form,
for item in A:
    print(item)
print("-----------")
  for item in B.keys():
    print(item)
print("-----------")
  for item in B.values():
    print(item)
print("-----------")
  for item in B.items():
    print(item)
    print("The value of keys is {} and the value of list of a key is {}".format(item[0],item[1]))
print("-----------")

Results are:

1
2
3
4
-----------
col1
col2
-----------
[1, 2, 3]
[4, 5, 6]
-----------
('col1', [1, 2, 3])
The value of keys is col1 and the value of list of a key is [1, 2, 3]
('col2', [4, 5, 6])
The value of keys is col2 and the value of list of a key is [4, 5, 6]
-----------

Some of the comments are right in saying that these answers do not correspond to the question.

One reason one might want to loop through a dictionary using "indexes" is for example to compute a distance matrix for a set of objects in a dictionary. To put it as an example (going a bit to the basics on the bullet below):

  • Assuming one have 1000 objects on a dictionary, the distance square matrix consider all combinations from one object to any other and so it would have dimensions of 1000x1000 elements. But if the distance from object 1 to object 2 is the same as from object 2 to object 1, one need to compute the distance only to less than half of the square matrix, since the diagonal will have distance 0 and the values are mirrored above and below the diagonal.

This is why most packages use a condensed distance matrix ( How does condensed distance matrix work? (pdist) )

But consider the case one is implementing the computation of a distance matrix, or any kind of permutation of the sort. In such case you need to skip the results from more than half of the cases. This means that a FOR loop that runs through all the dictionary is just hitting an IF and jumping to the next iteration without performing really any job most of the time. For large datasets this additional "IFs" and loops add up to a relevant amount on the processing time and could be avoided if, at each loop, one starts one "index" further on the dictionary.

Going than to the question, my conclusion right now is that the answer is NO. One has no way to directly access the dictionary values by any index except the key or an iterator.

I understand that most of the answers up to now applies different approaches to perform this task but really don't allow any index manipulation, that would be useful in a case such as exemplified.

The only alternative I see is to use a list or other variable as a sequential index to the dictionary. Here than goes an implementation to exemplify such case:

#!/usr/bin/python3

dishes = {'spam': 4.25, 'eggs': 1.50, 'sausage': 1.75, 'bacon': 2.00}
print("Dictionary: {}\n".format(dishes))

key_list = list(dishes.keys())
number_of_items = len(key_list)

condensed_matrix = [0]*int(round(((number_of_items**2)-number_of_items)/2,0))
c_m_index = 0

for first_index in range(0,number_of_items):
    for second_index in range(first_index+1,number_of_items):
        condensed_matrix[c_m_index] = dishes[key_list[first_index]] - dishes[key_list[second_index]]
        print("{}. {}-{} = {}".format(c_m_index,key_list[first_index],key_list[second_index],condensed_matrix[c_m_index]))
        c_m_index+=1

The output is:

Dictionary: {'spam': 4.25, 'eggs': 1.5, 'sausage': 1.75, 'bacon': 2.0}

0. spam-eggs = 2.75
1. spam-sausage = 2.5
2. spam-bacon = 2.25
3. eggs-sausage = -0.25
4. eggs-bacon = -0.5
5. sausage-bacon = -0.25

Its also worth mentioning that are packages such as intertools that allows one to perform similar tasks in a shorter format.


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


Since you want to iterate in order, you can use sorted:

for k, v in sorted(dict.items()):
    print k,v