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':'^',
Solution 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.
Solution 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.
Post a Comment for "How To Enumerate Items In A Dictionary With Enumerate( ) In Python"