Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Zip' dictionary of lists in Python

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

Example:

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

And I want the resulting list to be like this:

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

I assume there is an elegant way of doing this?

Edit:

I have compared running times of @Steve Jessop's namedtuple answer to the dictionary version by @Ashwini Chaudhary, and the former is somewhat faster:

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

Avg. of 100 runs:

namedtuple and map: 0.093583753109
namedtuple and zip: 0.119455988407
dictionary and zip: 0.159063346386
like image 777
rongved Avatar asked Feb 21 '14 09:02

rongved


People also ask

What does zip (*) do in Python?

The zip() function combines the contents of two or more iterables. zip() returns a zip object. This is an iterator of tuples where all the values you have passed as arguments are stored as pairs. Python's zip() function takes an iterable—such as a list, tuple, set, or dictionary—as an argument.

How do I zip in Python?

Create a zip archive from multiple files in Python Create a ZipFile object by passing the new file name and mode as 'w' (write mode). It will create a new zip file and open it within ZipFile object. Call write() function on ZipFile object to add the files in it. call close() on ZipFile object to Close the zip file.

Can we convert list to dictionary in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.


1 Answers

>>> 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}]
like image 196
Ashwini Chaudhary Avatar answered Oct 05 '22 06:10

Ashwini Chaudhary