Search code examples
python-3.xlistdictionarylambdafunctional-programming

List to dictionary using functional programming in python


I want to convert a list to dictionary using the rule x if x odd; (x*2, x*3) if x is even using functional programming in python.

Example list([1, 2, 3]) to dict({1:1, 4:2, 6:2, 3:3})

I have a code that converts list to {1: 1, (4, 2): (6, 2), 3: 3}

from itertools import chain
print(
    dict(
        map(
            lambda elem:
            (lambda x: (x, x))(elem) if elem % 2 == 1
            else (lambda x: chain(
                ((x*2, x), (x*3, x))
            ))(elem),
            list([1, 2, 3])
        )
    )
)

Could anyone figure it out?

The result should be the same as this code produces

d = dict()
for x in [1, 2, 3]:
    if x % 2 == 1:
        d[x] = x
    else:
        d[x*2] = x
        d[x*3] = x

Solution

  • You can simply use dictionary comprehension:

    lst = [1, 2, 3]
    
    out = {k: v for v in lst for k in ((v,) if v % 2 else (v * 2, v * 3))}
    print(out)
    

    Prints:

    {1: 1, 4: 2, 6: 2, 3: 3}
    

    EDIT: Without for-loops or any libraries:

    d = (
        dict(map(lambda x: (x, x), filter(lambda x: x % 2, lst)))
        | dict(map(lambda x: (x * 2, x), filter(lambda x: x % 2 == 0, lst)))
        | dict(map(lambda x: (x * 3, x), filter(lambda x: x % 2 == 0, lst)))
    )
    print(d)
    

    Prints:

    {1: 1, 3: 3, 4: 2, 6: 2}