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?
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.
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 [] .
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.
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.
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:]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With