使用条件语法从列表创建字典理解 [英] Create dictionary comprehension from list with condition syntax

查看:86
本文介绍了使用条件语法从列表创建字典理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用字典理解语法来创建字典.

I'd like to create a dictionary using dictionary comprehension syntax.

请注意,列表l包含字符串元组和带有第一个元素的元组始终是时间戳.

Note that list l contains tuples of strings and tuples with 1st element always a time stamp.

这有效:

d = {}
for entry in l:
    if entry[0] not in d:
        d[entry[0]] = []
    d[entry[0]].append(entry)

这不起作用:

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

推荐答案

您不能为此使用字典理解.对于每个迭代步骤(如果未过滤),将生成一个新的键值对.这意味着您无法更新另一个已经生成的键值对.

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.

只需坚持使用循环即可.您可以使用dict.setdefault()进行简化:

Just stick with the loop. You can simplify it with dict.setdefault():

d = {}
for entry in l:
    d.setdefault(entry[0], []).append(entry)

请注意,示例中的d在字典理解完成之前是不存在的;只有这样,d才会绑定到结果.更具体地说,是解决语法错误,Python将:之前的部分视为一个单独的表达式,以生成键值对中的键,并且其中的for ... in ...语法被解析为生成器表达式(形式为理解语法);您可以在这样的表达式中使用if进行过滤,但是在理解中可能没有else部分,因此该错误指向了else.

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.

这篇关于使用条件语法从列表创建字典理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆