0

I have made a small demo of a more complex problem

def f(a):
    return tuple([x for x in range(a)])

d = {}
[d['1'],d['2']] = f(2)
print d
# {'1': 0, '2': 1} 
# Works

Now suppose the keys are programmatically generated
How do i achieve the same thing for this case?

n = 10
l = [x for x in range(n)]
[d[x] for x in l] = f(n)
print d
# SyntaxError: can't assign to list comprehension
4
  • 3
    use a loop........ Commented Jul 28, 2016 at 8:32
  • 2
    {i+1:i for i in f(n)} Commented Jul 28, 2016 at 8:33
  • What is your expected result? Commented Jul 28, 2016 at 8:37
  • Note that there is no such thing as a list of variables - [d[x] for x in l] would create a list of the elements of d, which are objects, not variables. Basically, each d[x] doesn't resolve to "x'th position of d" but "object at x'th position of d". The outermost [] in [d['1'], d['2']] mean something different whether they are left or right elements of an assignment. Commented Jul 28, 2016 at 8:49

1 Answer 1

1

You can't, it's a syntactical feature of the assignment statement. If you do something dynamic, it'll use different syntax, and thus not work.

If you have some function results f() and a list of keys keys, you can use zip to create an iterable of keys and results, and loop over them:

d = {}
for key, value in zip(keys, f()):
    d[key] = value

That is easily rewritten as a dict comprehension:

d = {key: value for key, value in zip(keys, f())}

Or, in this specific case as mentioned by @JonClements, even as

d = dict(zip(keys, f()))
Sign up to request clarification or add additional context in comments.

1 Comment

Or... d = dict(zip(keys, f()))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.