Skip to content

Instantly share code, notes, and snippets.

@sirkonst
Last active September 18, 2015 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sirkonst/af906c479b570b148132 to your computer and use it in GitHub Desktop.
Save sirkonst/af906c479b570b148132 to your computer and use it in GitHub Desktop.
Generates all possible combinations of values for dictionary (useful for tests)
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