14

値がまだ設定されていない場合に値を設定する最もpythonicな方法は何ですか?dict

現時点では、私のコードは if ステートメントを使用しています:

if "timeout" not in connection_settings:
    connection_settings["timeout"] = compute_default_timeout(connection_settings)

dict.get(key,default)別の関数に渡される辞書を準備しているコードではなく、辞書を消費するコードに適しています。あなたは何かを設定するためにそれを使うことができますが、それはそれほどきれいではありません:

connection_settings["timeout"] = connection_settings.get("timeout", \
    compute_default_timeout(connection_settings))

dict にキーが含まれていても、compute 関数を評価します。バグ。

Defaultdict は、デフォルト値が同じ場合です。

もちろん、計算を必要としないプリミティブな値をデフォルトとして設定することはよくあります。もちろん、それらは を使用できますdict.setdefault。しかし、より複雑なケースはどうでしょうか?

4

8 に答える 8

4

これを行う1つの方法は次のとおりです。

if key not in dict:
  dict[key] = value
于 2013-04-12T07:09:07.060 に答える
0

おそらく必要ですdict.setdefault

新しい辞書を作成し、値を設定します。

>>> d = {}
>>> d.setdefault('timeout', 120)
120
>>> d
{'timeout': 120}

値がすでに設定されている場合は、dict.setdefaultそれを上書きしません:

>>> d['port']=8080
>>> d.setdefault('port', 8888)
8080
>>> d
{'port': 8080, 'timeout': 120}
于 2013-04-12T07:21:25.527 に答える
-1

キーが存在しない場合に高価なネットワーク要求の評価を延期するとともに、dict.get()メソッドの戻り値 (Falsy) を悪用することは便利で明白であることがわかりました。Noneor

d = dict()

def fetch_and_set(d, key):
    d[key] = ("expensive operation to fetch key")
    if not d[key]:
        raise Exception("could not get value")
    return d[key]

...

value = d.get(key) or fetch_and_set(d, key)

私の場合、具体的には、キャッシュから新しいfn()辞書を作成し、後で呼び出しを促進した後にキャッシュを更新していました。

これが私の使用法を簡略化したものです

j = load(database)  # dict
d = dict()

# see if desired keys are in the cache, else fetch
for key in keys:
    d[key] = j.get(key) or fetch(key, network_token)

fn(d)  # use d for something useful

j.update(d)  # update database with new values (if any)
于 2018-06-15T22:51:27.673 に答える