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
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.
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.
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.
>>> 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}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With