1

I need to convert a structure like this:

(1, 2, 3, 4, 5, 6)

To a dictionnary like this:

{1: 2, 3: 4, 5: 6}

How would you proceed ?

Pierre Barre
  • 2,174
  • 1
  • 11
  • 23

2 Answers2

3

Pair up the elements 2 by two and pass the result to dict():

result = dict(zip(*[iter(values)] * 2))

By using iter() here you avoid creating two in-memory list objects the way [::2] and [1::2] slicing would. See Iterating over every two elements in a list as to why this works.

Demo:

>>> values = (1, 2, 3, 4, 5, 6)
>>> dict(zip(*[iter(values)] * 2))
{1: 2, 3: 4, 5: 6}
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

The idea is to zip together two slices of the tuple with step 2 - first one starting with the 0th element and the second - with the 1st element, and then pass the result to the dict() constructor:

>>> t = (1, 2, 3, 4, 5, 6)
>>> dict(zip(t[::2], t[1::2]))
{1: 2, 3: 4, 5: 6}

Just to expand that, here are the intermediate values:

>>> t[::2]
(1, 3, 5)
>>> t[1::2]
(2, 4, 6)

Now the zip() would aggregate the elements together, group by position:

>>> zip(t[::2], t[1::2])
[(1, 2), (3, 4), (5, 6)]

Then, the dict() would make a dictionary out of the list of pairs using first elements of the items as keys and second elements as values.

Note that the downside of this approach is that there would be two extra lists created in memory as opposed to @Martijn's proposal. Though, this approach is arguably simpler and more readable.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195