Search code examples
pythondictionarydictionary-comprehension

Expanding a list into a dictionary in python through a transformation function returning key-value pairs


I'm trying to generate a dictionary from a list and a function that computes a key-value pair from an element of said list, such as in

def transform(element):
    key = f"{element}^2"
    value = element**2
    return key, value

elements = [1, 2, 3]
elements_dict = {k: v for (k, v) in [transform(elem) for elem in elements]}

# elements_dict should be {'1^2': 1, '2^2': 4, '3^2': 9}

However, this list of elements can be very large and needs to be processed in a timely fashion, which makes it both impractical and inefficient to generate the intermediary array.

Is there a way to do this so that the elements are read lazily from the original list, transformed into the key value pairs by the function, and stored in the dictionary without generating any intermediary structures?

The use of the transform function is also non-negotiable; provided here is a minimum working sample, however they actual function is much more complex and can't simply be written as part of the dictionary comprehension.


Solution

  • You can use the built-in map function.

    elements_dict = {k: v for (k, v) in map(transform, elements)}