[Python] How do you extract key/value from a function in a dict comprehension?

Discussão em 'Python' iniciado por Stack, Maio 31, 2025.

  1. Stack

    Stack Membro Participativo

    I have a function foo that generates a key and value from a string. I want to use that function in a dict comprehension, but haven't figured out how to extract multiple values from a single iteration of the function.

    The catch is that foo could be expensive or stateful or executed remotely, so I can't call it more than once per iteration.

    Example:

    def foo(s): # simple placeholder for an expensive function
    return s[0], s[1:]


    print([foo(s) for s in ['abcd', 'efg', 'hi']])
    print({foo(s) for s in ['abcd', 'efg', 'hi']})
    print({foo(s)[0]: foo(s)[1] for s in ['abcd', 'efg', 'hi']})


    Output:

    [('a', 'bcd'), ('e', 'fg'), ('h', 'i')] # List comprehension works
    {('a', 'bcd'), ('e', 'fg'), ('h', 'i')} # Set comprehension works
    {'a': 'bcd', 'e': 'fg', 'h': 'i'} # Desired dict output, but function is called twice


    How can I extract k: v from a single invocation of the function?

    Continue reading...

Compartilhe esta Página