Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')]
}
like image 866
user46543 Avatar asked Sep 29 '19 03:09

user46543


1 Answers

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')]}
like image 182
Ajax1234 Avatar answered Nov 14 '22 23:11

Ajax1234