assign values to list of variables in python -


i have made small demo of more complex problem

def f(a):     return tuple([x x in range(a)])  d = {} [d['1'],d['2']] = f(2) print d # {'1': 0, '2': 1}  # works 

now suppose keys programmatically generated
how achieve same thing case?

n = 10 l = [x x in range(n)] [d[x] x in l] = f(n) print d # syntaxerror: can't assign list comprehension 

you can't, it's syntactical feature of assignment statement. if dynamic, it'll use different syntax, , not work.

if have function results f() , list of keys keys, can use zip create iterable of keys , results, , loop on them:

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

that rewritten dict comprehension:

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

or, in specific case mentioned @jonclements, as

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

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -