Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 383
Benny McFarley Avatar asked Jun 09 '26 08:06

Benny McFarley


1 Answers

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.

like image 100
Patrick Haugh Avatar answered Jun 11 '26 20:06

Patrick Haugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!