How to make dictionary from list

Question:

I have this variables:

fab_centrum = ['A', 'B'] 
sales_line = ['1AA', '2BB', '3CC', '1AA', '2BB', '3CC']
keys = ['feasibility_score', 'capacity_score']
feasibility_score = [10,30,40, 10,30,40]
capacity_score = [50,60,70, 50,60,70]

And I would like to make dic with this structure

    bach = {
                A: {'1AA': {
                  feasibility_score: 10,
                  capacity_score: 50,
                  }
                  '2BB': {
                  feasibility_score: 10,
                  capacity_score: 50,
                  }
                   }
                  
           B: {'1AA': {
                  feasibility_score: 10,
                  capacity_score: 50,
                  }
....
                }
    
    
    }

I know I can use something like

batch = dict.fromkeys(fab_centrum, sales_line)

But I dont know how to make dict with nested values like my structue.
I am new to python

Asked By: onhalu

||

Answers:

Is the result below what you want instead?

It looks strange that sales_line, feasibility_score, and capacity_score have duplicate elements inside…but feel free to add them back as long as they have the same length so that zip() won’t cut some elements off.

More on the collections module: https://docs.python.org/3/library/collections.html#module-collections

More on the zip()function: https://docs.python.org/3/library/functions.html#zip

from collections import defaultdict

fab_centrum = ['A', 'B']
sales_line = ['1AA', '2BB', '3CC']
keys_ = ['feasibility_score', 'capacity_score']
feasibility_score = [10, 30, 40]
capacity_score = [50, 60, 70]

batch = defaultdict(dict)
for sl, fs, cs in zip(sales_line, feasibility_score, capacity_score):
    for char in fab_centrum:
        batch[char][sl] = {keys_[0]: fs, keys_[1]: cs}

print(batch)

Result:

{
'A': 
    {
    '1AA':{'feasibility_score': 10, 'capacity_score': 50}, 
    '2BB':{'feasibility_score': 30, 'capacity_score': 60}, 
    '3CC':{'feasibility_score': 40, 'capacity_score': 70}
    }, 

'B': 
    {
    '1AA': {'feasibility_score': 10, 'capacity_score': 50}, 
    '2BB': {'feasibility_score': 30, 'capacity_score': 60}, 
    '3CC': {'feasibility_score': 40, 'capacity_score': 70}
    }
}
Answered By: コリン
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.