-1

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 1
    d = {k[0].append(k) for k in l if k[0] in d else k[0]:k for k in l}
                                                   ^
SyntaxError: invalid syntax
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
ptay
  • 736
  • 6
  • 11
  • This is doubly tricky because even if you get it into a syntactically valid form, you won't be able to do `k[0] in d` inside the statement that creates d, because d doesn't exist yet. – Kevin Sep 19 '17 at 15:34

1 Answers1

5

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343