Dictionary of "Zip" Lists in Python

I have a dictionary of lists, and I want to combine them into a single namedtuples list. I want the first element of all lists in the first tuple, the second in the second, etc.

Example:

{'key1': [1, 2, 3], 'key2': [4, 5, 6], 'key3': [7, 8, 9]}

And I want the resulting list to look like this:

[('key1': 1, 'key2': 4, 'key3': 7), 
('key1': 2, 'key2': 5, 'key3': 8), 
('key1': 3, 'key2': 6, 'key3': 9)]

I guess there is an elegant way to do this?

Edit:

I compared the running time of @Steve Jessop with the name tuple to the dictionary version by @Ashwini Chaudhary, and the first is somewhat faster:

d = {key: numpy.random.random_integers(0, 10000, 100000) 
        for key in ['key1', 'key2', 'key3']}

Avg. from 100 runs:

namedtuple and map: 0.093583753109
namedtuple and zip: 0.119455988407
dictionary and zip: 0.159063346386
+4
source share
2 answers

Get the keys first. You can sort them or whatever, at this point. You may know which keys to use in which order, so you don't need to check the data.

keys = list(d.keys())

:

Record = collections.namedtuple('Record', keys)

:

[Record(*t) for t in zip(*(d[k] for k in keys))]

list(map(Record, *(d[k] for k in keys))), map.

, keys list(d.keys()), d.values() (d[k] for k in keys), , , . , namedtuple, :

Record = collections.namedtuple('Record', d.keys())
[Record(*t) for t in zip(*(d.values()))]

list(map(Record, *d.values())), map.

+5
>>> d = {'key1': [1, 2, 3], 'key2': [4, 5, 6], 'key3': [7, 8, 9]}
>>> keys = d.keys()
>>> [dict(zip(keys, vals)) for vals in zip(*(d[k] for k in keys))]
[{'key3': 7, 'key2': 4, 'key1': 1},
 {'key3': 8, 'key2': 5, 'key1': 2},
 {'key3': 9, 'key2': 6, 'key1': 3}]
+5

Source: https://habr.com/ru/post/1528064/


All Articles