简体   繁体   中英

Python: convert Dictionary of lists to list of tuples

I want to convert dictionary of lists to list of tuple
Here is an example: entry data

d = {
u'x_axis': [1,2,3,7,8,9],
u'y_axis': [5,6,5,6,5,6],
u'z_axis': [1,2,1,2,1,2],
}

What I want to have is:

l = [
(1,5,1),
(2,6,2),
(3,5,1),
(7,6,2),
(8,5,1),
(9,6,2),
]

The lists in dictionary are same length.

So as you can see, x_axis is in 1st possition in every tuple etc.

A bit like rotation it by -90 degrees

Edit.1
I want to have the same order of elements in tuples as order of keys and number of keys is not defined by default. So I could have write keys to some var like: keys = d.keys() if I do: l = here what I want with vars in tuples in order of keys-list

Using zip :

>>> d = {
...     u'x_axis': [1,2,3,7,8,9],
...     u'y_axis': [5,6,5,6,5,6],
...     u'z_axis': [1,2,1,2,1,2],
... }
>>> list(zip(d['x_axis'], d['y_axis'], d['z_axis']))
[(1, 5, 1), (2, 6, 2), (3, 5, 1), (7, 6, 2), (8, 5, 1), (9, 6, 2)]

list(..) is not needed in Python 2.x. (In Python 2.x, zip returns a list, in Python 3.x, zip returns an iterator)

UPDATE

Using pre-defined keys:

>>> keys = 'x_axis', 'y_axis', 'z_axis'  # OR keys = sorted(d)
>>> list(zip(*(d[key] for key in keys)))
[(1, 5, 1), (2, 6, 2), (3, 5, 1), (7, 6, 2), (8, 5, 1), (9, 6, 2)]

NOTE: keys = d.keys() will not work because Python dictionary does not guarantee key order.

You can use zip function :

>>> zip(*d.values())
[(5, 1, 1), (6, 2, 2), (5, 3, 1), (6, 7, 2), (5, 8, 1), (6, 9, 2)]

If you care about the order you should pass the values by a custom order to zip function.for example :

zip(d['x_axis'], d['y_axis'], d['z_axis'])

Or use an collections.OrderedDict if you want to use values() and unpacking :

>>> from collections import OrderedDict
>>> d=OrderedDict([(u'x_axis', [1, 2, 3, 7, 8, 9]),(u'y_axis', [5, 6, 5, 6, 5, 6]), (u'z_axis', [1, 2, 1, 2, 1, 2])])
>>> 
>>> zip(*d.values())
[(1, 5, 1), (2, 6, 2), (3, 5, 1), (7, 6, 2), (8, 5, 1), (9, 6, 2)]
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM