Skip to content

Instantly share code, notes, and snippets.

@SteadBytes
Created February 11, 2019 16:40
Show Gist options
  • Save SteadBytes/6d988fe8a9743303047a87302b2e22c7 to your computer and use it in GitHub Desktop.
Save SteadBytes/6d988fe8a9743303047a87302b2e22c7 to your computer and use it in GitHub Desktop.
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