0

How can I write a list comprehension to enumerate key: value pairs into 3-membered tuples from a Python dictionary?

d = {'one': 'val1', 'two': 'val2', 'three': 'val3', 'four': 'val4', 'five': 'val5'}

When I try this:

li = [(index, k, val) for index, k, val in enumerate(d.items())]

I get a ValueError: need more than 2 values to unpack

The desired output would be:

[(0, 'one', 'val1'),
 (1, 'two', 'val2'),
 (2, 'three', 'val3'),
 (3, 'four', 'val4'),
 (4, 'five', 'val5')]
turtle
  • 7,533
  • 18
  • 68
  • 97

2 Answers2

4

Nest your tuples. But the order may not be as desired.

li = [(index, k, val) for index, (k, val) in enumerate(d.items())]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

The output of enumerate() is a 2-element tuple. Since the value of that tuple is another 2-element tuple, you need to use parentheses to group them.

li = [(index, k, val) for index, (k, val) in enumerate(d.items())]

However, since a dict is by default unordered, you need to create an OrderedDict.

odict = collections.OrderedDict()
odict['one'] = 'val1'
odict['two'] = 'val2'
odict['three'] = 'val3'
odict['four'] = 'val4'

li = [(index, k, val) for (index, (k, val)) in enumerate(odict.items())]

This would give you the following value for li

[(0, 'one', 'val1'), (1, 'two', 'val2'), (2, 'three', 'val3'), (3, 'four', 'val4')]
Rajesh J Advani
  • 5,585
  • 2
  • 23
  • 35