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

孤街浪徒 提交于 2021-01-28 09:36:54

问题


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


回答1:


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.




回答2:


As in Alexandre's comment, the code would work like this:

for (i, (name, sym)) in enumerate(example_dict.items()):
    print(i, name, sym)

A comment about style: while comprehension is really neat when computing values, using it for a loop of printing would work, but would obfuscate the intent of your code, making it less readable.



来源:https://stackoverflow.com/questions/61595308/how-to-enumerate-items-in-a-dictionary-with-enumerate-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!