Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid syntax using dict comprehension

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?

like image 236
Chris Avatar asked Jun 07 '12 14:06

Chris


People also ask

What is dict comprehension in Python?

Dictionary comprehension is a method for transforming one dictionary into another dictionary. During this transformation, items within the original dictionary can be conditionally included in the new dictionary and each item can be transformed as needed.

What is the syntax for list comprehension?

List comprehension is considerably faster than processing a list using the for loop. As per the above syntax, the list comprehension syntax contains three parts: an expression, one or more for loop, and optionally, one or more if conditions. The list comprehension must be in the square brackets [] .

Can you use list comprehension for dictionaries?

Method 1: Using dict() methodUsing dict() method we can convert list comprehension to the dictionary. Here we will pass the list_comprehension like a list of tuple values such that the first value act as a key in the dictionary and the second value act as the value in the dictionary.

What does this list comprehension do?

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.


1 Answers

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:]))
like image 164
Daniel Roseman Avatar answered Nov 07 '22 14:11

Daniel Roseman