Created
February 11, 2019 16:40
-
-
Save SteadBytes/6d988fe8a9743303047a87302b2e22c7 to your computer and use it in GitHub Desktop.
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
from itertools import combinations | |
from typing import Dict | |
def dictionary_combinations(d: Dict, min_keys=1, max_keys=None): | |
""" | |
Produce all possible combinations of sub-dictionaries from a dictionary | |
within a length range. | |
>>> dictionary_combinations({'key1': 1, 'key2': 2, 'key3': 3}) | |
[{'key1': 1}, | |
{'key2': 2}, | |
{'key3': 3}, | |
{'key1': 1, 'key2': 2}, | |
{'key1': 1, 'key3': 3}, | |
{'key2': 2, 'key3': 3}, | |
{'key1': 1, 'key2': 2, 'key3': 3}] | |
>>> dictionary_combinations({'key1': 1, 'key2': 2, 'key3': 3}, max_keys=2) | |
[{'key1': 1}, | |
{'key2': 2}, | |
{'key3': 3}, | |
{'key1': 1, 'key2': 2}, | |
{'key1': 1, 'key3': 3}, | |
{'key2': 2, 'key3': 3}] | |
""" | |
num_keys_range = range(min_keys, (max_keys if max_keys else len(d)) + 1) | |
return [_d for l in num_keys_range for _d in map(dict, combinations(d.items(), l))] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment