2

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

2 Answers2

10

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Oh did you mean I should use comprehension only for like print stuff from a list and not use a for loop for printing out stuff from a list with modifiers like enumerate etc.? – Humble_Snowman May 04 '20 at 15:18
  • 1
    @Humble_Snowman I mean, list comprehensions are meant for building lists, but your end goal is actually to print, not build a list. The list that gets built is `[None, None, None, None]`, which is pointless. – wjandrea May 04 '20 at 15:34
1

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.

Amitai Irron
  • 1,973
  • 1
  • 12
  • 14
  • I didn't understand "using it for a loop of printing". Can you explain it in simpler terms? – Humble_Snowman May 04 '20 at 15:14
  • 1
    You used a comprehension expression for printing: [print(i,j,a) for (i,j,a) in enumerate(example_dict.items())] There are two problems with this: 1) you a computing a list (possibly a big one) of None values (which are returned by print); 2) You hide what should be, and, in my code, evidently is, an output operation, inside an expression of a computation. – Amitai Irron May 04 '20 at 15:35