Miroslav Kašpar
Miroslav Kašpar

Reputation: 79

Combinations of elements to form nested dictionary

I have a dictionary, with integers as key (1 up to n), and values being lists (1 up to m elements). I would like to create a new dictionary, with the primary key being an integer (1 up to each n * m), and the secondary key the original n key with values as strings from the list.

Input:

input = {
        1: ['foo', ...],
        2: ['buz', ...],
        3: ['sam', 'foo', ...],
        4: ['bar', ...],
        5: ['foo', 'bar', ...]
        ...
        }

Where ... marks more values being present. Values are sometimes the same, sometimes not, and order is not important here even though I used lists.

Output: for this particular case (if ... omitted).

output = {
         1: {1: 'foo', 2: 'buz', 3: 'sam', 4: 'bar', 5: 'foo'},
         2: {1: 'foo', 2: 'buz', 3: 'sam', 4: 'bar', 5: 'bar'},
         3: {1: 'foo', 2: 'buz', 3: 'bar', 4: 'bar', 5: 'foo'},
         4: {1: 'foo', 2: 'buz', 3: 'bar', 4: 'bar', 5: 'bar'}
         }

Edit: second example

input = {
        1: ['alice'],
        2: ['tom', 'josh'],
        3: ['mike', 'adam'],
        4: ['kate', 'filip'],
        }

output = {
         1: {1: 'alice', 2: 'tom', 3: 'mike', 4: 'kate'},
         2: {1: 'alice', 2: 'tom', 3: 'mike', 4: 'filip'},
         3: {1: 'alice', 2: 'tom', 3: 'adam', 4: 'kate'},
         4: {1: 'alice', 2: 'tom', 3: 'adam', 4: 'filip'},
         5: {1: 'alice', 2: 'josh', 3: 'mike', 4: 'kate'},
         6: {1: 'alice', 2: 'josh', 3: 'mike', 4: 'filip'},
         7: {1: 'alice', 2: 'josh', 3: 'adam', 4: 'kate'},
         8: {1: 'alice', 2: 'josh', 3: 'adam', 4: 'filip'},
         }

If someone has at least a hint I would very much appreciate it. Since I can't find the working solution at all.

Thanks all in advance

Upvotes: 1

Views: 74

Answers (1)

mozway
mozway

Reputation: 262359

You can use itertools.product and a nested dictionary comprehension:

from itertools import product
out = {i+1: {j+1: e for j,e in enumerate(x)}
       for i,x in enumerate(product(*data.values()))}

output:

{1: {1: 'foo', 2: 'buz', 3: 'sam', 4: 'bar', 5: 'foo'},
 2: {1: 'foo', 2: 'buz', 3: 'sam', 4: 'bar', 5: 'bar'},
 3: {1: 'foo', 2: 'buz', 3: 'foo', 4: 'bar', 5: 'foo'},
 4: {1: 'foo', 2: 'buz', 3: 'foo', 4: 'bar', 5: 'bar'}}

Input:

data = {1: ['foo'], 2: ['buz'], 3: ['sam', 'foo'], 4: ['bar'], 5: ['foo', 'bar']}

Upvotes: 1

Related Questions