user46543
user46543

Reputation: 1053

Generate Python dictionary from combination of lists

I've tried to solve my issue but I could not.

I have three Python lists:

atr = ['a','b','c']
m = ['h','i','j']
func = ['x','y','z']

My problem is to generate a Python dictionary based on the combination of those three lists:

The desired output:

py_dict = {
    'a': [('x','h'), ('x','i'), ('x','j'), ('y','h'), ('y','i'), ('y','j'),('z','h'), ('z','i'), ('z','j')],
    'b': [('x','h'), ('x','i'), ('x','j'), ('y','h'), ('y','i'), ('y','j'),('z','h'), ('z','i'), ('z','j')],
    'c': [('x','h'), ('x','i'), ('x','j'), ('y','h'), ('y','i'), ('y','j'),('z','h'), ('z','i'), ('z','j')]
}

Upvotes: 6

Views: 119

Answers (1)

Ajax1234
Ajax1234

Reputation: 71451

You can use itertools.product:

import itertools
atr = ['a','b','c']
m = ['h','i','j']
func = ['x','y','z']
prod = list(itertools.product(func, m))
result = {i:prod for i in atr}

Output:

{'a': [('x', 'h'), ('x', 'i'), ('x', 'j'), ('y', 'h'), ('y', 'i'), ('y', 'j'), ('z', 'h'), ('z', 'i'), ('z', 'j')], 'b': [('x', 'h'), ('x', 'i'), ('x', 'j'), ('y', 'h'), ('y', 'i'), ('y', 'j'), ('z', 'h'), ('z', 'i'), ('z', 'j')], 'c': [('x', 'h'), ('x', 'i'), ('x', 'j'), ('y', 'h'), ('y', 'i'), ('y', 'j'), ('z', 'h'), ('z', 'i'), ('z', 'j')]}

Upvotes: 7

Related Questions