What I want to do is simple:
collection = {'a':[], 'b':[], 'c':[]}
values = [1,2,3]
I want to make a function that produces the following: (append the values into the list element of the dictionary, the dic and the list are the same length)
{'a':[1], 'b':[2], 'c':[3]}
This is simple enough and I can do it using, a couple of for x in. But I want to do this in one line. (using two loops in the same line) and I can not get the syntax to work.
I have tried some things similar to this, but they all result in syntax error:
collection[c].append(value), for c in d.iteritems(), for value in values
You can’t do what you want to do on one line. You can create a new dictionary on one line though:
Result:
This is called a dict comprehension. Like a list comprehension and a generator expression, you can use multiple loops in one of those, but you don’t need one here.
zip()will pair up the keys fromcollectionwith the integers fromvalues.To modify a
dictin-place, you’ll have to use 2 lines at least:Python does accept that on one line, but that goes against just about every styleguide I can look up for you:
Python throws a syntax error because it interprets your line as a tuple of expressions (the commas make it a tuple), and two of your expressions are
forstatements, which cannot be used in an expression.