FaCoffee
FaCoffee

Reputation: 7929

Python: create two lists from dict with list of tuples

Given this dict:

d={0: [(78.65, 89.86),
  (28.0, 23.0),
  (63.43, 9.29),
  (66.47, 55.47),
  (68.0, 4.5),
  (69.5, 59.0),
  (86.26, 1.65),
  (84.2, 56.2),
  (88.0, 18.53),
  (111.0, 40.0)], ...}

How do you create two lists, such that y takes the first element of each tuple and x takes the second, for each key in d?

In the example above (only key=0 is shown) this would be:

y=[78.65, 28.0, 63.43, 66.47, 68.0, 69.5, 86.26, 84.2, 88.0, 111.0]
x=[89.86, 23.0, 9.29, 55.47, 4.5, 59.0, 1.65, 56.2, 18.53, 40.0]

My attempt is wrong (I tried the x list only):

for j,v in enumerate(d.values()):    
   x=[v[i[1]] for v in d.values() for i in v]

Because:

TypeError                                 Traceback (most recent call last)
<ipython-input-97-bdac6878fe6c> in <module>()
----> 1 x=[v[i[1]] for v in d.values() for i in v]

TypeError: list indices must be integers, not numpy.float64

What's wrong with this?

Upvotes: 0

Views: 617

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477318

If I understood your comment correctly, you want to obtain the x and y coordinates of the tuple list that is associated with key 0. In that case you can simply use zip(..) and map(..) to lists:

y,x = map(list,zip(*d[0]))

If you do not want to change x and y later in your program - immutable lists are basically tuples, you can omit the map(list,...):

y,x = zip(*d[0]) # here x and y are tuples (and thus immutable)

Mind that if the dictionary contains two elements, like:

{0:[(1,4),(2,5)],
 1:[(1,3),(0,2)]}

it will only process the data for the 0 key. So y = [1,2] and x = [4,5].

Upvotes: 4

Jos&#233; S&#225;nchez
Jos&#233; S&#225;nchez

Reputation: 1136

Do you mean something like this?

z = [i for v in d.values() for i in v]
x, y = zip(*z)

Upvotes: 2

Related Questions