我想做这样的事情:
parsetable = {
# ...
declarations: {
token: 3 for token in [_id, _if, _while, _lbrace, _println]
}.update({_variable: 2}),
#...
}
但是这不起作用,因为更新不会返回任何内容.除了明确地编写整个dict之外,有没有简单的方法呢?
应该可以使用dict()和元组的列表理解额外部分,但这很尴尬.
最佳答案 我认为你提到的使用dict()和元组列表的方法就是我这样做的方式:
dict([(x, 3) for x in [_id, _if, _while, _lbrace, _println]] + [(_variable, 2)])
如果你真的想要使用字典理解,你可以这样做:
{ x : 2 if x == _variable else 3
for x in [_id, _if, _while, _lbrace, _println, _variable] }