Create dictionary comprehension from list with condition syntax

…衆ロ難τιáo~ 提交于 2019-12-25 18:14:21

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/46304423/create-dictionary-comprehension-from-list-with-condition-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!