Skip to content

Instantly share code, notes, and snippets.

@Gab-km
Last active August 29, 2015 14:07
Show Gist options
  • Save Gab-km/571a3f48367bdae17f17 to your computer and use it in GitHub Desktop.
Save Gab-km/571a3f48367bdae17f17 to your computer and use it in GitHub Desktop.
2つの dict の和を取る関数(キー重複は後勝ち)
def add_dict(this, other):
"""2つの dict の和を取る関数(キー重複は後勝ち)
@this ベースとなる dict オブジェクト
@other 追加される dict オブジェクト
@return 2つの dict を合成した dict
"""
result = this.copy()
for key in other:
result[key] = other[key]
return result
# Thanks to @wonderful_panda ! ;-)
def add_dict_nicely(this, other):
"""2つの dict の和を取る関数(キー重複は後勝ち)
@this ベースとなる dict オブジェクト
@other 追加される dict オブジェクト
@return 2つの dict を合成した dict
"""
result = this.copy()
result.update(other)
return result
# Thanks to @cocoatomo ! ;-)
def add_dict_lovely(this, other):
"""2つの dict の和を取る関数(キー重複時の結果は実装依存)
@this ベースとなる dict オブジェクト
@other 追加される dict オブジェクト
@return 2つの dict を合成した dict
"""
return dict(this.items() | other.items())
# Thanks to @kk6 ! ;-)
def add_dicts(this, *others):
"""2つの dict の和を取る関数(キー重複は後勝ち)
@this ベースとなる dict オブジェクト
@others 追加される dict オブジェクト(複数)
@return 2つの dict を合成した dict
"""
from functools import reduce
return reduce(lambda base, dicts: dict(base, **dicts), (this,) + others)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment