Skip to content

Instantly share code, notes, and snippets.

@Ogaday
Last active March 9, 2020 12:36
Show Gist options
  • Save Ogaday/f08d825debfaf04074c223d7ad89db05 to your computer and use it in GitHub Desktop.
Save Ogaday/f08d825debfaf04074c223d7ad89db05 to your computer and use it in GitHub Desktop.
Tranpose Dict

Dictionary puzzle of the week:

The objective is to write an expression or function that, given a dictionary in which each value is a list, transpose it so the result is list of dictionaries, where:

  • The keys of each new dictionary are the same as the keys of the original dictionary
  • The values of the ith dictionary correspond to the ith elements of the values of the original dictionary

If that doesn't make sense, here's an example:

# Input:
d = {'a': [4, 5, 6], 'b': [7, 8, 9]}
# Expected Output:
[{'a': 4, 'b': 7}, {'a': 5, 'b': 8}, {'a': 6, 'b': 9}]

For instance, the function might have the following signature:

def transpose_dict(d: Dict[str, List[int]]) -> List[Dict[str, int]]: ...

Edge cases:

  • Think about how to handle an empty dict, or values lists of length 0.
  • What about if the values lists have different lengths?
from typing import Dict, Iterable, List
def transpose(d: Dict[str, List[int]]) -> Iterable[Dict[str, int]]:
"""
>>> d = {'a': [4, 5, 6], 'b': [7, 8, 9]}
>>> list(iterrows(d))
[{'a': 4, 'b': 7}, {'a': 5, 'b': 8}, {'a': 6, 'b': 9}]
"""
yield from (dict(zip(d.keys(), row)) for row in zip(*d.values()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment