Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the key of an item when doing a FOR loop through a dictionary or list in Python?

Tags:

python

I am new to Python.

Say I have a list:

list = ['A','B','C','D']

The key for each item respectively here is 0,1,2,3 - right?

Now I am going to loop through it with a for loop...

for item in list:
    print item

That's great, I can print out my list.

How do I get the key here? For example being able to do:

print key
print item

on each loop?

If this isn't possible with a list, where keys are not declared myself, is it possible with a Dictionary?

Thanks

like image 505
Mike Avatar asked Jun 10 '10 22:06

Mike


People also ask

Can you iterate through keys in a dictionary Python?

You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

How do you iterate through a list in a dictionary Python?

In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example. You can iterate keys by using the dictionary object directly in a for loop.


2 Answers

The answer is different for lists and dicts.

A list has no key. Each item will have an index. You can enumerate a list like this:

>>> l = ['A','B','C','D']
>>> for index, item in enumerate(l):
...     print index
...     print item
... 
0
A
1
B
2
C
3
D

I used your example here, but called the list 'l', to avoid a clash with a reserved word.

If you iterate over a dict, you are handed the key:

>>> d = {0: 'apple', 1: 'banana', 2: 'cherry', 3: 'damson', }
>>> for k in d:
...     print k
...     print d[k]
... 
0
apple
1
banana
2
cherry
3
damson
like image 161
Johnsyweb Avatar answered Sep 28 '22 00:09

Johnsyweb


You want the index, not the key. For this you can use enumerate:

for index, item in enumerate(l):
    print index
    print item

This is mentioned in the section Looping Techniques in the Python tutorial which also covers looping over dictionaries while getting both the key and the value.

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
...     print k, v
...
gallahad the pure
robin the brave
like image 41
Mark Byers Avatar answered Sep 28 '22 02:09

Mark Byers