Skip to content

Instantly share code, notes, and snippets.

@1Mark
Last active August 22, 2021 15:59
Show Gist options
  • Save 1Mark/60758cefb9ceeb5f1d6d4f25d96bcd6a to your computer and use it in GitHub Desktop.
Save 1Mark/60758cefb9ceeb5f1d6d4f25d96bcd6a to your computer and use it in GitHub Desktop.
How to get all subsets of a dictionary in python?
from itertools import combinations
from typing import List
def subsets(the_dict: dict) -> List[dict]:
subsets_as_tuples = []
dict_as_tuple = the_dict.items()
# We start from 1 in the range since list(combinations(some_dict, 0)) returns an empty list
for i in range(1, len(the_dict) + 1):
subsets_as_tuples.extend(list(combinations(dict_as_tuple, i)))
print(subsets_as_tuples)
# prints
# [(('a', 1),),
# (('b', 2),),
# (('c', 3),),
# (('a', 1), ('b', 2)),
# (('a', 1), ('c', 3)),
# (('b', 2), ('c', 3)),
# (('a', 1), ('b', 2), ('c', 3))]
return [dict(key_sublist_list) for key_sublist_list in subsets_as_tuples]
x = dict(a=1, b=2, c=3)
subsets(x)
# returns
# [{'a': 1},
# {'b': 2},
# {'c': 3},
# {'a': 1, 'b': 2},
# {'a': 1, 'c': 3},
# {'b': 2, 'c': 3},
# {'a': 1, 'b': 2, 'c': 3}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment