From 1bf7eb28c4eca269cdfb51a69a071933e29eb9b9 Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Thu, 16 Apr 2020 19:28:35 +0300 Subject: [PATCH] Add merge_dictionaries --- snippets/merge_dictionaries.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 snippets/merge_dictionaries.md diff --git a/snippets/merge_dictionaries.md b/snippets/merge_dictionaries.md new file mode 100644 index 000000000..7a0ec9b63 --- /dev/null +++ b/snippets/merge_dictionaries.md @@ -0,0 +1,27 @@ +--- +title: merge_dictionaries +tags: dictionary,intermediate +--- + +Merges two or more dictionaries. + +Create a new `dict()` and loop over `dicts`, using `dictionary.update()` to add the key-value pairs from each one to the result. + +```py +def merge_dictionaries(*dicts): + res = dict() + for d in dicts: + res.update(d) + return res +``` + +```py +ages_one = { + "Peter": 10, + "Isabel": 11, +} +ages_two = { + "Anna": 9 +} +merge_dictionaries(ages_one, ages_two) # { "Peter": 10, "Isabel": 11, "Anna": 9 } +```