【发布时间】:2012-05-10 13:53:13
【问题描述】:
可以使用生成器创建字典 (PEP-289):
dict((h,h*2) for h in range(5))
#{0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
在同一个 dict() 调用中是否可以在语法上添加一些额外的键值对?以下语法不正确,但更好地解释了我的问题:
dict((h,h*2) for h in range(5), {'foo':'bar'})
#SyntaxError: Generator expression must be parenthesized if not sole argument
换句话说,是否可以在单个 dict() 调用中构建以下内容:
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 'foo': 'bar' }
【问题讨论】: