1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Example of merging a dictionary with default values into an existing dictionary with values in #python (I don't want to write if 'key' in dict anymore ..)

Last updated at Posted at 2019-04-15

another answers here comments

#python で値を持った既存の辞書に、デフォルト値つきの辞書をマージする例 ( もう if 'key' in dict なんて書きたくないんですよ‥ ) - Qiita


Using collections defaultdict and ChainMap together

wanna do

  • This dictionary d = {"a":1, "b",2}
  • When calling this way d["c"]
  • I want the default value to be entered instead of KeyError

example

 from collections import defaultdict 
 import collections 
 
 existing_dict = {"a":1, "b":2} 
 
 default_dict = defaultdict(int) 
 
 merged_dict = collections.ChainMap(existing_dict, default_dict) 
 

EXE

 Python 3.7.2 (default, Jan 13 2019, 12:50:01) 
 [Clang 10.0.0 (clang-1000.11.45.5)] on darwin 
 Type "help", "copyright", "credits" or "license" for more information. 
 >>> from collections import defaultdict 
 >>> import collections 
 >>> existing_dict = {"a":1, "b":2} 
 >>> default_dict = defaultdict(int) 
 >>> merged_dict = collections.ChainMap(existing_dict, default_dict) 
 >>> merged_dict["a"] 
 1 
 >>> merged_dict["b"] 
 2 
 >>> merged_dict["c"] 
 0 
 >>> merged_dict["d"] 
 0 
 

ps

  • Maybe we aren't doing something really careless
  • Please write from the white goat if something is wrong

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?