【发布时间】:2016-10-01 18:13:02
【问题描述】:
在 python 3.5 中,我们可以通过使用 double-splat unpacking 来合并 dicts
>>> d1 = {1: 'one', 2: 'two'}
>>> d2 = {3: 'three'}
>>> {**d1, **d2}
{1: 'one', 2: 'two', 3: 'three'}
酷。不过,它似乎不能推广到动态用例:
>>> ds = [d1, d2]
>>> {**d for d in ds}
SyntaxError: dict unpacking cannot be used in dict comprehension
相反,我们必须使用reduce(lambda x,y: {**x, **y}, ds, {}),这看起来更丑陋。为什么解析器不允许使用“一种明显的方法”,而该表达式似乎没有任何歧义?
【问题讨论】:
-
您也不能在任何其他 *- 或 **- 解包上下文中执行此操作。即,你不能做
some_function(*x for x in list_lists)。拆包星不是真正的运算符,不能出现在表达式中。 -
{k: v for d in [d1, d2] for k, v in d.items()}将替代您的reduce(),尽管“丑陋”仍然。 -
我相信另一种选择是
dict(ChainMap(d2, d1)),我个人不喜欢它,因为到底谁知道ChainMap是什么? -
其实,
ChainMap(*ds)本身似乎就足够了!很好,您应该将其添加为答案。 -
叹息....
{**d for d in ds}会很不错的。
标签: python dictionary syntax-error python-3.5 dict-comprehension