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
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.
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.
The answer is different for list
s and dict
s.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With