Last active
September 18, 2015 09:58
-
-
Save sirkonst/af906c479b570b148132 to your computer and use it in GitHub Desktop.
Generates all possible combinations of values for dictionary (useful for tests)
This file contains hidden or 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 | |
def combinations_dict(data): | |
""" | |
Generates all possible combinations of values for dictionary. | |
At the entrance you can pass either dictionary or list of tuples. | |
Examples:: | |
combinations_dict({ | |
'a': 'A', 'b': 'B', 'c': 'C' | |
}) | |
>> {'a': 'A'} | |
>> {'c': 'C'} | |
>> {'b': 'B'} | |
>> {'a': 'A', 'b': 'B'} | |
>> {'a': 'A', 'c': 'C'} | |
>> {'b': 'B', 'c': 'C'} | |
>> {'a': 'A', 'b': 'B', 'c': 'C'} | |
combinations_dict([ | |
('a', 'A'), ('b', 'B_1'), ('b', 'B_2'), | |
]) | |
>> {'a': 'A'} | |
>> {'b': 'B_1'} | |
>> {'b': 'B_2'} | |
>> {'a': 'A', 'b': 'B_1'} | |
>> {'a': 'A', 'b': 'B_2'} | |
:param dict or list of tuples data: | |
:return dict: | |
""" | |
if isinstance(data, dict): | |
_items = lambda: data.iteritems() | |
keys_count = len(data) | |
elif isinstance(data, list): | |
_items = lambda: data | |
keys_count = len(set(x[0] for x in _items())) | |
else: | |
raise ValueError | |
for count in xrange(1, keys_count+1): | |
for p in combinations(_items(), count): | |
rt = dict(p) | |
if len(rt) == count: | |
yield rt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment