forked from Chalarangelo/30-seconds-of-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request Chalarangelo#435 from 30-seconds/combine-values
Add combine_values
- Loading branch information
Showing
1 changed file
with
28 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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} | ||
``` |