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
Iterate over all key-value pairs of dictionary by index As we passed the sequence returned by items() to the enumerate() function with start index 0 (default value). Therefore it yielded each item (key-value) of dictionary along with index, starting from 0.
You can find a dict index by counting into the dict. keys() with a loop. If you use the enumerate() function, it will generate the index values automatically.
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 >>>
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
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