2017-11-16 7 views
1

おそらく、私はBrand Xプログラミング言語に甘んじているかもしれませんが、次の点でより良いpythonicイディオムがありますか?Python辞書のエントリを作成または更新する

thing_dict = {} 

def find_or_create_thing(key): 
    if (thing_dict.has_key(key)): 
     thing = thing_dict[key] 
    else: 
     thing = create_new_thing(key) 
     thing_dict[key] = thing 
    return thing 

これは1〜2行で実行できるようです。私はConditional Expressionを使うことを考えましたが、Pythonの奇妙な構文は単に読みやすくするためのものではありませんでした。

また、私はtry: ... except KeyError:と考えましたが、それはちょうど同じくらいの量のテキストであり、おそらくかなりのオーバーヘッドです。

P.S.私はS.Oについてプログラミングスタイルの質問をすることを知っています。問題があるが、私は自分のチャンスを取るよ...

答えて

1

inを使用して、あなたが絶対に2本のライン上の機能が必要な場合は、よりPython的

thing_dict = {} 

def find_or_create_thing(key): 
    if not key in thing_dict: 
     thing_dict[key] = create_new_thing(key) 
    return thing_dict[key] 

です:

thing_dict = {} 

def find_or_create_thing(key): 
    if not key in thing_dict: thing_dict[key] = create_new_thing(key) 
    return thing_dict[key] 
+0

もう1つはineffです'create(new)'が 'get()'のそれぞれに対して呼び出されるので、望ましくない副作用を引き起こす可能性があります。 –

+0

2番目のアプローチの問題は、 'create_new_thing(key)'は常に –

+0

と呼ばれています。 – alexisdevarennes

1

あまり短くしますしかし、おそらく「もっときれい」(ユースケースに応じて):

class ThingDict(dict): 
    def __missing__(self, key): 
     self[key] = create_new_thing(key) 
     return self[key] 

thing_dict = ThingDict() 

def find_or_create_thing(key): 
    return thing_dict[key] 
+0

これは今までthing_dictを更新しますか? – alexisdevarennes

+1

@alexisdevarennes Ups、no。私はそれを訂正しました。 –

関連する問題