I have this function and I would like to make a dictionary in the same way but with just one-liner using lambda expression (most probably)
def make_dict():
y = {}
for i in range(0, 10, 2):
y[i] = i+1
y[i+1] = i
return y
I could not make it, since all lambda expressions that are for a specific pattern and cannot assign the second element in the dictionary with respect to the first one
I could not make it, since all lambda expressions that are for a specific pattern and cannot assign the second element in the dictionary with respect to the first one
I have already tried:
{(i if i%2==0 else i+1) :(i+1 if i%2==0 else i) for i in range(0, 10, 2)}
I expect the result to be:
{0: 1, 1: 0, 2: 3, 3: 2, 4: 5, 5: 4, 6: 7, 7: 6, 8: 9, 9: 8}
>Solution :
One solution can be using dict-comprehension:
out = {i: i - 1 if i % 2 else i + 1 for i in range(10)}
print(out)
Prints:
{0: 1, 1: 0, 2: 3, 3: 2, 4: 5, 5: 4, 6: 7, 7: 6, 8: 9, 9: 8}