Search code examples
pythondictionaryfor-looplist-comprehensionenumerate

How to enumerate items in a dictionary with enumerate( ) in python


As the title suggests I wanted to enumerate the key and its values (without brackets) in python. I tried the following code :

example_dict = {'left':'<','right':'>','up':'^','down':'v',}
[print(i,j,a) for (i,j,a) in enumerate(example_dict.items())]

But it doesn't work. I want the output to be like this

0 left <
1 right >
2 up ^
3 down v

Thank you in advance


Solution

  • In this case enumerate returns (index, (key, value)), so you just need to change your unpacking to for i, (j, a), though personally I would use k, v instead of j, a in an example.

    for i, (k, v) in enumerate(example_dict.items()):
        print(i, k, v)
    

    BTW, don't use a comprehension for side effects; just use a for-loop.