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?
How about this with dict()
and a generator expression? The dict
constructor can take an iterable of tuples, with each tuple representing a key and associated value.
print(dict(foo(s) for s in ['abcd', 'efg', 'hi']))
Working demo: https://www.online-python.com/ME7cP0L6Hw