0

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?

3
  • 2
    It's not clear to me what should happen if the dictionary contains two elements... Commented Feb 28, 2017 at 15:43
  • You mean another list of tuples with key=1? In that case, not much, because I want to extract these two lists inside a for loop, so that at each iteration they are something different. Does this answer your question? Commented Feb 28, 2017 at 15:45
  • 3
    x=[i[1] for v in d.values() for i in v] should work for your snippet Commented Feb 28, 2017 at 15:46

2 Answers 2

4

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].

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, I am. These coordinates are returned in the form (row, column).
Or, in python 3 it produces iterators, which python unpacks into tuples.
I like this solution, but what if y,x = zip(*d[0]) was nested in a for loop to iterate over all keys? Is it enough changing it to y,x = zip(*d[i])?
@CF84: Yes. If you use for i in d: it will fetch for each key and obtain x and y for that key.
2

Do you mean something like this?

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

1 Comment

Why do you construct a new tuple and do not return i itself?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.