簡體   English   中英

Pythonic的方法是從dict理解中創建字典,+其他東西

[英]Pythonic way to write create dictionary from dict comprehension, + something else

我想做這樣的事情:

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] }

但是,只是為了讓你知道,如果你想更新返回somethign,你可以寫一個像這樣的函數:

import copy
def updated_dict(first_dict, second_dict):
    f = copy.deepcopy(first_dict)
    f.update(second_dict)
    return f

為了清晰起見,我將其分開然后應用@Mark Byers的第二個建議來理解字典:

type2 = [_variable]
type3 = [_id, _if, _while, _lbrace, _println]

parsetable = {
    declarations: { token : 2 if token in type2 else 3 for token in type2+type3 }
}

這使得事物非常清晰並且是可擴展的,同時將相關項目保持在一起以便於查找和/或修改。

這里的內容類似於@Ant提到的應用於您的示例數據的內容:

def merged_dicts(dict1, *dicts):
    for dict_ in dicts:
        dict1.update(dict_)
    return dict1

parsetable = {
    declarations:
        merged_dicts(
            { token: 3 for token in [_id, _if, _while, _lbrace, _println] },
            { _variable: 2 }
        ),
}

我離開了初步的copy.deepcopy() ,因為沒有必要使用這種類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM