Search code examples
python-3.xdictionary-comprehension

Dictionary comprehension - dynamically generate key-value pairs?


I want to achieve the same result of

{i: i+1 for i in range(4)} # {0: 1, 1: 2, 2: 3, 3: 4}

But dynamically generate key: value part with myfunc(i), how do I do that?

Functions that return {i: i+1} or (i, i+1) won't work:

{{i: i+1} for i in range(4)} # TypeError: unhashable type: 'dict'

Solution

  • dict(map(myfunc, range(4)))
    

    See: https://docs.python.org/3.9/library/stdtypes.html#dict

    Example:

    >>> dict([(1,2), (3,4)])
    {1: 2, 3: 4}
    >>> dict(map(lambda x: (x, x+1), range(4)))
    {0: 1, 1: 2, 2: 3, 3: 4}