From 05683b9bde217558f92647294ad5a98b56940034 Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Sun, 7 Mar 2021 12:30:47 +0200 Subject: [PATCH] Add combine_values --- snippets/combine_values.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 snippets/combine_values.md diff --git a/snippets/combine_values.md b/snippets/combine_values.md new file mode 100644 index 000000000..e8dc1cdc7 --- /dev/null +++ b/snippets/combine_values.md @@ -0,0 +1,28 @@ +--- +title: combine_values +tags: dictionary,intermediate +--- + +Combines two or more dictionaries, creating a list of values for each key. + +- Create a new `collections.defaultdict` with `list` as the default value for each key and loop over `dicts`. +- Use `dict.append()` to map the values of the dictionary to keys. +- Use `dict()` to convert the `collections.defaultdict` to a regular dictionary. + +```py +from collections import defaultdict + +def combine_values(*dicts): + res = defaultdict(list) + for d in dicts: + for key in d: + res[key].append(d[key]) + return dict(res) +``` + +```py +d1 = {'a': 1, 'b': 'foo', 'c': 400} +d2 = {'a': 3, 'b': 200, 'd': 400} + +combine_values(d1, d2) # {'a': [1, 3], 'b': ['foo', 200], 'c': 400, 'd': 400} +```