gaurav gupta gaurav gupta - 3 months ago 6
Python Question

assign values to list of variables in python

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


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()))