Skip to content

Instantly share code, notes, and snippets.

@claytonjroberts
Last active August 24, 2023 18:01
Show Gist options
  • Save claytonjroberts/99b4f7b05df7dd7437eb03dc0afe45b9 to your computer and use it in GitHub Desktop.
Save claytonjroberts/99b4f7b05df7dd7437eb03dc0afe45b9 to your computer and use it in GitHub Desktop.
Python 3: Permutations of a dict of lists into a list of dicts
"""Get all combinations of values of a dictionary and return a list of dictionaries"""
import itertools
d = {1: [1, 2, 3, 4], 2: [5, 6], 3: [7]}
final = [
{k: v for k, v in zip(sorted(d.keys()), list_prod_value)}
for list_prod_value in itertools.product(*(d[k] for k in sorted(d.keys())))
]
# Will output:
[{1: 1, 2: 5, 3: 7},
{1: 1, 2: 6, 3: 7},
{1: 2, 2: 5, 3: 7},
{1: 2, 2: 6, 3: 7},
{1: 3, 2: 5, 3: 7},
{1: 3, 2: 6, 3: 7},
{1: 4, 2: 5, 3: 7},
{1: 4, 2: 6, 3: 7}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment