Transpose (rotate) a list file in python

I have a dictionary that looks like this:

{'x': [1, 2, 3], 'y': [4, 5, 6]}

I want to convert it to the following format:

[{'x': 1, 'y': 4}, {'x': 2, 'y': 5}, {'x': 3, 'y': 6}] 

I can do this with explicit loops, but is there a good pythonic way to do this?

Edit: It turns out there is a similar question here , and one of the answers is similar to the accepted answer here, but the author of this answer writes: "I do not recommend using such code in any real system." Can someone explain why such code is bad? It seems very elegant to me.

+4
source share
3 answers

zip() , , dict.items(), dict , :

[dict(zip(d, col)) for col in zip(*d.values())]

zip(*d.values()) , zip(d, col) .

:

[dict(zip(('x', 'y'), col)) for col in zip(d['x'], d['y'])]

.

:

>>> d = {'x': [1, 2, 3], 'y': [4, 5, 6]}
>>> [dict(zip(d, col)) for col in zip(*d.values())]
[{'x': 1, 'y': 4}, {'x': 2, 'y': 5}, {'x': 3, 'y': 6}]
+9

, , 1- (, , , 1-...;) - , ( dict, ).

dict, , , , (, 2).

dicts 2 . x, y.

new_dicts = [{'x': x} for x in d['x']]
for new_dict, y in zip(new_dicts, d['y']):
    new_dict['y'] = y

1 , , :

new_dicts = [{'x': x, 'y': y} for x, y in zip(d['x'], d['y'])]

, ...

import operator
value_getter = operator.itemgetter(*list_of_keys)
new_dicts_values = zip(*value_getter(d))
new_dicts = [
    dict(zip(list_of_keys, new_dict_values))
    for new_dict_values in new_dicts_values]

, ... , , . , , , zipping dict , ...

, , ,

list_of_keys = list(d)
+2

d = {'x': [1, 2, 3], 'y': [4, 5, 6]}

:

keys = d.keys()

print map(lambda tupl: map(lambda k,v: {k:v}, keys, tupl), zip(*d.itervalues()))

It looks pythonic, but for large recordings, the overhead of lambda calls each time the card calls the lambda function will increase.

+1
source

All Articles