Unpack specific dictionary values to list of tuples

Viewed 17

I have a dataset in the following structure:

mydict = {"key1": [1, 2, 3],
          "key2": [9],
          "key3": [4, 5, 6],
          "key4": [10]}

I wish to extract specific values from the keys, so the structure will be:

desired_output = [(1, 9, 4, 10), (2, 9, 5, 10), (3, 9, 6, 10)]

What I've tried: I extracted the values by duplicating the values in key2 and key4, so the 'len' of all keys is the same. Then consecutively:

desired_output = []

for row in range(len(mydict['key1'])):
    res = [t[row] for t in mydict.values()]
    desired_output.append(tuple(res))

However, the real dataset is large, 'key1' and 'key3' have over 2,000 values (equal len). Therefore, I am wondering if there is a more elegant way to do this (without duplicating the values in key2, key4).

I researched stack topics, but this didn't solve my question yet. Some of these related topics are: Select specific elements from a dictionary with tuple values Python converting the values from dicts into a tuples

I am eager to learn from you

1 Answers

One possible solution is to use itertools.zip_longest.

If your lists doesn't contain None you can try (if yes, use other fillvalue=):

from itertools import zip_longest

mydict = {"key1": [1, 2, 3], "key2": [9], "key3": [4, 5, 6], "key4": [10]}

out = []
for t in zip_longest(*mydict.values()):
    out.append(
        tuple(mydict[k][-1] if v is None else v for k, v in zip(mydict, t))
    )

print(out)

Prints:

[(1, 9, 4, 10), (2, 9, 5, 10), (3, 9, 6, 10)]

One-liner:

out = [
    tuple(mydict[k][-1] if v is None else v for k, v in zip(mydict, t))
    for t in zip_longest(*mydict.values())
]
Related