Generate Python dictionary from combination of lists
Asked Answered
L

1

6

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')]
}
Lisa answered 29/9, 2019 at 3:17 Comment(0)
C
7

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')]}
Carin answered 29/9, 2019 at 3:21 Comment(1)
Thanks bro, Oh God, I just know if Python has this kind of function.Lisa

© 2022 - 2024 — McMap. All rights reserved.