59

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
leerssej
  • 14,260
  • 6
  • 48
  • 57
Dev.K.
  • 2,428
  • 5
  • 35
  • 49

9 Answers9

137

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
>>> 
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 9
    it is important to note that dictionaries are unordered and any change may result in different indices for all items – Joran Beasley Jul 22 '13 at 17:11
  • 3
    Unless of course you will use OrderedDict: https://docs.python.org/2/library/collections.html#collections.OrderedDict – Datageek Nov 03 '14 at 15:19
  • 4
    OR: Unless you use cpython >= 3.6, which retains the insertion order. – Victoria Feb 13 '19 at 04:31
  • 3
    NB: `iteritems()` is probably intended for older python versions, try `for key, value in dict.items(): print(key, value)` for python3 – Eiriks Sep 14 '22 at 11:44
92

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

Serguei Fedorov
  • 7,763
  • 9
  • 63
  • 94
3

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
untitled90
  • 98
  • 5
2

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.

Fábio Lobão
  • 171
  • 1
  • 11
1

Do this:

for i in dict.keys():
  dict[i]
Mark Nenadov
  • 6,421
  • 5
  • 24
  • 32
1

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

for k, v in sorted(dict.items()):
    print k,v
jh314
  • 27,144
  • 16
  • 62
  • 82
1

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.

lalebarde
  • 1,684
  • 1
  • 21
  • 36
0

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]
-----------
Dr Neo
  • 724
  • 6
  • 11
-30

I can't think of any reason why you would want to do that. If you just need to iterate over the dictionary, you can just do.

for key, elem in testDict.items():
    print key, elem

OR

for i in testDict:
     print i, testDict[i]
Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
  • 93
    This doesn't answer the question. It doesn't matter if you can't understand why someone would want to do it. A correct answer is given by @alecxe: http://stackoverflow.com/a/17793421/835428 – Rik Smith-Unna Mar 27 '14 at 11:33
  • 8
    Why is this accepted as the answer by the OP? since it's not an answer to the actual question asked by the OP. weird. – Michahell Apr 09 '15 at 01:59
  • 2
    @RikSmith-Unna It matters if you can't understand. Because knowing the bigger picture might reveal a better/simpler solution. And if so, you must ask the OP about it (the bigger picture). – x-yuri Aug 01 '17 at 20:25
  • To everyone who is downvoting this answer, my intent to ask about the reason was the XY problem. Please read about it here - https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – Sukrit Kalra Jan 10 '18 at 05:54
  • 1
    If the OP is able to explain why he needs this particular type of iteration, we might be able to come up with a better solution or a change in the way he is designing his code, which would go a long way than doing a particularly expensive operation. – Sukrit Kalra Jan 10 '18 at 05:54
  • One reason could be to display dict of objects in a table. – Saren Tasciyan Nov 05 '20 at 14:20