私はPythonで行っているクールなプロジェクトに取り組んでおり、ループが通過できる回数(最大再帰深度)を制限することでサイズを制限するため、再帰なしでこれを行う方法が必要でした。この関数は、任意のサイズのネスト辞書で機能する必要があります。ネストされた辞書の特定のキーからエントリを追加したり、値を取得、変更、または削除したりするにはどうすればよいですか?SOでこれに対する適切な答えは見つかりませんでした。これらはすべて、過度に複雑であるか、再帰を使用しているためです。
まあ、あなたはまた別の方法に行くことができます:
d = {}
my_keystring = "fruits.orange.price"
d[my_keystring] = 5.75
print(F"Demo get value: {d[my_keystring]}\nThis is the PRICE of ORANGE in FRUITS.")
d[my_keystring] = 1.25
print(F"Demo set value: {d[my_keystring]}\nThis is the NEW PRICE of ORANGE in FRUITS!")
del d[my_keystring]
print(F"Demo del entry: fruits.orange.price is now {d.get(my_keystring)}!")
d['fruits.orange.in_stock'] = True
print(F"Demo add entry! Added a new entry called in_stock to fruits.orange, it's value is: {d['fruits.orange.in_stock']}")
どちらが得ます
Demo get value: 5.75
This is the PRICE of ORANGE in FRUITS.
Demo set value: 1.25
This is the NEW PRICE of ORANGE in FRUITS!
Demo del entry: fruits.orange.price is now None!
Demo add entry! Added a new entry called in_stock to fruits.orange, it's value is: True
これを正確に行うこの機能を示すこの単純なモジュールを作成しました。キーパス自体を知っている必要があります。あなたはデモを取り出してから、それをつかんで任意のプロジェクトで使用することができますGitHubの本がでライセンスされているとして、MITライセンス。楽しい!
これがベンチマークされるのを見るのは興味深いでしょう。
'''
MIT License
Copyright (c) 2019 Keith Cronin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.'''
d = {}
d['fruits'] = {}
d['fruits']['orange'] = {}
d['fruits']['orange']['price'] = 5.75
my_keystring = "fruits.orange.price"
def get_value(keystring, dictionary):
amountkeys = keystring.count('.')+1
lastfoundindex = 0
counter = 0
while counter < amountkeys:
if counter == 0:
value = dictionary[keystring[lastfoundindex:keystring.find('.')]]
elif counter == amountkeys - 1:
value = value[keystring[lastfoundindex:]]
break
else:
value = value[keystring[lastfoundindex:keystring.find('.',lastfoundindex)]]
lastfoundindex = keystring.find('.',lastfoundindex)+1
counter += 1
return value
print(F"Demo get_value(): {get_value(my_keystring, d)}\nThis is the PRICE of ORANGE in FRUITS.")
def set_value(keystring, dictionary, new_value):
amountkeys = keystring.count('.')+1
lastfoundindex = 0
counter = 0
while counter < amountkeys:
if counter == 0:
value = dictionary[keystring[lastfoundindex:keystring.find('.')]]
elif counter == amountkeys - 1:
value[keystring[lastfoundindex:]] = new_value
break
else:
value = value[keystring[lastfoundindex:keystring.find('.',lastfoundindex)]]
lastfoundindex = keystring.find('.',lastfoundindex)+1
counter += 1
value = new_value
return value
print(F"Demo set_value(): {set_value(my_keystring, d, 1.25)}\nThis is the NEW PRICE of ORANGE in FRUITS!")
def del_entry(keystring, dictionary):
amountkeys = keystring.count('.')+1
lastfoundindex = 0
counter = 0
while counter < amountkeys:
if counter == 0:
value = dictionary[keystring[lastfoundindex:keystring.find('.')]]
elif counter == amountkeys - 1:
del value[keystring[lastfoundindex:]]
break
else:
value = value[keystring[lastfoundindex:keystring.find('.',lastfoundindex)]]
lastfoundindex = keystring.find('.',lastfoundindex)+1
counter += 1
del_entry('fruits.orange.price',d)
print(F"Demo del_entry(): fruits.orange.price is now {get_value('fruits.orange', d)}!")
def add_entry(keystring, dictionary, entry_name, entry_value = None):
amountkeys = keystring.count('.')+1
lastfoundindex = 0
counter = 0
while counter < amountkeys:
if counter == 0:
value = dictionary[keystring[lastfoundindex:keystring.find('.')]]
elif counter == amountkeys - 1:
value[keystring[lastfoundindex:]][entry_name] = entry_value
break
else:
value = value[keystring[lastfoundindex:keystring.find('.',lastfoundindex)]]
lastfoundindex = keystring.find('.',lastfoundindex)+1
counter += 1
add_entry('fruits.orange', d, 'in_stock', True)
print(F"Demo add_entry()! Added a new entry called in_stock to fruits.orange, it's value is: {get_value('fruits.orange.in_stock',d)}")
Reba McEntire が息子の Shelby Blackstock と共有しているクリスマスの伝統について学びましょう。
メーガン・マークルとマライア・キャリーが自然な髪の上でどのように結合したかについて、メーガンの「アーキタイプ」ポッドキャストのエピソードで学びましょう.
ハリー王子が家族、特にチャールズ王とウィリアム王子との関係について望んでいると主張したある情報源を発見してください。
ワイノナ・ジャッドが、母親のナオミ・ジャッドが亡くなってから初めての感謝祭のお祝いを主催しているときに、彼女が今では家長であることをどのように認識したかを学びましょう.
Air travel is far more than getting from point A to point B safely. How much do you know about the million little details that go into flying on airplanes?
The world is a huge place, yet some GeoGuessr players know locations in mere seconds. Are you one of GeoGuessr's gifted elite? Take our quiz to find out!
ここLifehackerでは大きな年でした。一緒に、私たちはミツバチを救おうとし、ハッキングされ、太陽をじっと見つめ、グロスチェーンレストランの食べ物を食べ、核爆弾から身を隠しました。
写真:ゲッティイメージズ経由のハーバート・ドーフマン/コービスさて、昨日、幼い子供たちにマジシャンズを見させて銃を飛び越えていたようです。知っておくと良い!昨夜、娘と私はシカゴの素晴らしいビンテージシアターであるミュージックボックスで映画を見に行きました。年齢に関係なく、誰も問題を抱えてはいけません。それは素晴らしい人生です。
Tomorrow's Kitchen シリコンストレッチ蓋 12個パック | $14 | アマゾン | プロモーション コード 20OFFKINJALids は基本的にキッチンの靴下です。常に迷子になり、二度と閉じられない孤立したコンテナーが残ります。しかし、蓋が伸びて、残った容器、鍋、フライパン、さらには大きなスライスされた果物のすべてに適合するとしたらどうでしょうか? その非常に特殊な蓋を失うことを二度と心配する必要はありません。
ロシアのフィギュアスケーター、カミラ・バリエバが関与したドーピング事件が整理されているため、チームは2022年北京冬季オリンピックで獲得したメダルを待っています。
何千人ものAmazonの買い物客がMulberry Silk Pillowcaseを推奨しており、現在販売中. シルクの枕カバーにはいくつかの色があり、髪を柔らかく肌を透明に保ちます。Amazonで最大46%オフになっている間にシルクの枕カバーを購入してください
ラファイエット警察署は、「不審な男性が女性に近づいた」という複数の苦情を受けて、12 月にパデュー大学の教授の捜査を開始しました。
私たちの周りの世界と同じように、言語は常に変化しています。以前の時代では、言語の変化は数年または数十年にわたって発生していましたが、現在では数日または数時間で変化する可能性があります。
認知症を患っている 91 歳のアジア人女性が最近、47 番街のアウター サンセット地区でロメオ ロレンゾ パーハムに襲われました。伝えられるところによると、被害者はサンフランシスコの通りを歩いていたところ、容疑者に近づき、攻撃を受け、暴行を受けました。
Cómo mejoramos la accesibilidad de nuestro componente de precio, y cómo nos marcó el camino hacia nuevos saberes para nuestro sistema de diseño. Por Ana Calderon y Laura Sarmiento Leer esta historia en inglés.
“And a river went out of Eden to water the garden, and from thence it was parted and became into four heads” Genesis 2:10. ? The heart is located in the middle of the thoracic cavity, pointing eastward.