Benny McFarley
Benny McFarley

Reputation: 89

Uniquely combining 3 lists into 1 with dictionary comprehension in Python

I am new to learning Python and I'm a few 100s lines of code in!

start = ['12', '08', '07', '16', '04']
middle = ['01', '01', '01', '01', '01']
end = ['13', '07', '08', '15', '05']

Desired output (in order):

[('1201': '13'), ('0801': '07'), ('0701': '08'), ('1601': '15'), ('0401', '05')]

The below code will fail to keep the original order (I'm stuck using python 3.4 and know 3.7+ would resolve this)

Combined_Lists = {start+middle: end for start, middle, end in zip(start, middle, end)}

When I try the below, it errors

from collections import OrderedDict
Combined_Lists = {start+middle: end for start, middle, end in OrderedDict(zip(start, middle, end))}

error:

ValueError: too many values to unpack (expected 2)

What am I missing here?

Upvotes: 3

Views: 53

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 60984

Your zip is producing 3 values, but OrderedDict requires an iterable of (key, value) pairs.

od = OrderedDict((s+m, e) for s, m, e in zip(start, middle, end))

You can't unpack this into a regular dictionary afterwards because then you will lose the order.

Your desired output is a list, so you might be looking for

[(s+m, e) for s, m, e in zip(start, middle, end)]

instead.

Upvotes: 6

Related Questions