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

Posted by Mike Hayes on Stack Overflow See other posts from Stack Overflow or by Mike Hayes
Published on 2010-06-10T22:38:34Z Indexed on 2010/06/10 22:42 UTC
Read the original article Hit count: 158

Filed under:

Hi

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

© Stack Overflow or respective owner

Related posts about python