Created
March 20, 2020 11:06
-
-
Save willprice/f2858912a9e869bcad23ca1f9e83a19a to your computer and use it in GitHub Desktop.
Collate a list of dictionaries into a dictionary of lists
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
__all__ = ['collate_dicts'] | |
from typing import List, Dict, Any | |
from collections import defaultdict | |
def collate_dicts(ds: List[Dict[Any, Any]]) -> Dict[Any, List[Any]]: | |
""" | |
Args: | |
ds: A list of dictionarys all with the same keys. | |
Returns: | |
A dictionary of values collated across | |
""" | |
if len(ds) == 0: | |
return defaultdict(lambda: []) | |
first_dict = ds[0] | |
keys = first_dict.keys() | |
collated = defaultdict(lambda: []) | |
for d in ds: | |
for k in keys: | |
collated[k].append(d[k]) | |
return dict(collated) | |
def test_collate_dicts(): | |
assert collate_dicts([])['a'] == [] | |
assert collate_dicts([dict(a=1, b=2), dict(a=2, b=3)]) == dict(a=[1, 2], b=[2, 3]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment