Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

One-liner python dictionary

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading