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
Post a Comment