Snowman08 Snowman08 - 21 days ago 6
Python Question

Issues with a 3 list combination into one dictonary

Question is how would I combine three list's together while iterating through them.

To explain it:



list_a has a bunch of the same keys
list_b has values
list_c has values
*Do the list have to be in order and what if they aren't????


Here are my list:



#list_a would be the key

list_a = ['MACHINE TOOLS', 'MACHINE TOOLS', 'FLUID', 'MACHINE TOOLS','MACHINE TOOLS', 'VALVES', 'FLUID', 'VALVES']

list_b = ['GROUP A MTOOLS', 'GROUP B MTOOLS', 'GROUP C MTOOLS', 'GROUP D MTOOLS', 'GROUP A FLUID', 'GROUP B FLUID', 'GROUP A VALVES', 'GROUP B VALVES']

list_c = ['1', '2', '3', '44', '46', '47', '52', '53']


here is what I would like to see come out of this



{
'MACHINE TOOLS': { 'GROUP A MTOOLS': '1', 'GROUP B MTOOLS': '2', 'GROUP C MTOOLS': '3', 'GROUP D MTOOLS': '44'},

'FLUID': {'GROUP A FLUID': '46', 'GROUP B FLUID': '47'},

'VALVES': {'GROUP A VALVES': '52', 'GROUP B VALVES': '53'}

}


What I've tried:



dic={ list_as:{ list_bs:[list_c] for list_bs in list_bs} for list_as in list_a}


^This comes out close to what I want but for some reason list_c's values aren't being iterated-- I've tried a for loop with them and still no luck.

Answer

Okay, since the keys in the first dictionary don't line up with the keys in the second, it looks like you're first going to have to define a static mapping between some of these names. That would look something like:

name_mapping = {"MTOOLS": "MACHINE TOOLS",
                "FLUID": "FLUID",
                "VALVES": "VALVES"}

Then, create a blank version of the output dictionary.

output = {key:{} for key in set(list_a)}

And finally, update that dict with the values from the other two lists:

for inner_key, val in zip(list_b, list_c):
    for name, real_name in name_mapping.items():
        if inner_key.endswith(name):
            output[real_name][inner_key] = val

That results in this for the lists you presented:

{'FLUID': {'GROUP A FLUID': '46', 'GROUP B FLUID': '47'},
 'MACHINE TOOLS': {'GROUP A MTOOLS': '1',
                   'GROUP B MTOOLS': '2',
                   'GROUP C MTOOLS': '3',
                   'GROUP D MTOOLS': '44'},
 'VALVES': {'GROUP A VALVES': '52', 'GROUP B VALVES': '53'}}

If the values in your lists lined up (e.g. 'MACHINE TOOLS' always appeared at the same index in list_a as something that ended with 'MTOOLS' in list_b), then this solution could be simplified.

Comments