问题
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