5

Given a list of floats named 'x', I would like to create a dict mapping each x in x[1:-1] to it's neighbors using a dict comprehension. I have tried the following line :

neighbours = {x1:(x0,x2) for (x0,x1,x2) in zip(x[:-2],x[1:-1],x[2:])}

However, the syntax seems to be invalid. What am I doing wrong?

Wooble
  • 87,717
  • 12
  • 108
  • 131
Chris
  • 531
  • 5
  • 11

1 Answers1

23

Dict comprehensions are only available in Python 2.7 upwards. For earlier versions, you need the dict() constructor with a generator:

dict((x1, (x0,x2)) for (x0,x1,x2) in zip(x[:-2],x[1:-1],x[2:]))
Will
  • 24,082
  • 14
  • 97
  • 108
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895