I'd like to create a dictionary using dictionary comprehension syntax.
Note that list l
contains tuples of strings and tuples with 1st element always a time stamp.
This works:
d = {}
for entry in l:if entry[0] not in d:d[entry[0]] = []d[entry[0]].append(entry)
This doesn't work:
d = {k[0].append(k) for k in l if k[0] in d else k[0]:k for k in l}File "<stdin>", line 1d = {k[0].append(k) for k in l if k[0] in d else k[0]:k for k in l}^
SyntaxError: invalid syntax
You can't use a dictionary comprehension for this. For each iteration step (if not filtered), a new key-value pair is produced. That means you can't update another, already generated key-value pair.
Just stick with the loop. You can simplify it with dict.setdefault()
:
d = {}
for entry in l:d.setdefault(entry[0], []).append(entry)
Note that d
in your example won't exist until the dictionary comprehension has completed; only then is d
bound to the result. And more specifically addressing the syntax error, Python sees the part before the :
as a separate expression to produce the key in the key-value pair, and the for ... in ...
syntax there is being parsed as a generator expression (a form of comprehension syntax); you can use if
in such an expression to filter, but there is no else
part possible in a comprehension, hence the error pointing at else
there.