Imagine a theoretical snippet:
# just for this example: `bad_structure` contains a list of dicts with different keys
# for the same semantic
bad_structure = [{'path': '/dir/one'}, {'subdir': '/dir/two'}]
# i want to turn this into
# { '/dir/one': some_func('/dir/one'),
# '/dir/two': some_func('/dir/two')}
result = {}
for e in bad_structure:
# calculate a value which we will need more than once (here the key)
p = next(k for k in ('path', 'subdir') if k in e)
result[p] = some_func(p)
I want to turn this into a dict comprehension now and my first approach looks like this:
bad_structure = [{'path': '/dir/one'}, {'path': '/dir/two'}]
result = {next(k for k in ('path', 'subdir') if k in e):
some_func(next(k for k in ('path', 'subdir') if k in e))
for e in bad_structure}
which contains the 'calculation' twice which ugly, error prone and slow. I would like to rewrite it to s.th. like
result = {p: some_func(p)
for p = next(k for k in ('path', 'subdir') if k in e)
for e in bad_structure}
which is no valid Python code of course..
Is something like this possible in Python?
For clarification: I don't care about comprehension syntax but reusing a calculation without separate variable declaration (which is not possible in closed expressions)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…