Forum Archive

Setting values to each items in a list of a nested dictionary

multitech_news

I'm trying to programmatically set a values to each item in a list inside a nested dictionary.

for example, let's say my initial dictionary, which I constructed is:

{'Abraham': {'subjects': ['Chem', 'Bio', 'Phy', 'Math']}}

Given some lists of values:

assess_type = ['Quiz', 'HW', 'ATTND', 'Exam']

chem = ['127', '135', '17', '46']
bio = ['154', '64', '14', '54']
phy = ['115', '115', '15', '55']
math = ['140', '160', '20', '40']
And I want to achieve a result like this:

{'Abraham': {'subjects': [
 'Chem': {'Quiz': '127', 'HW': '135', 'ATTND': '17', 'Exam': '46'},
 'Bio': {'Quiz': '154', 'HW': '64', 'ATTND': '14', 'Exam': '54'} ,
 'Phy': {'Quiz': '115', 'HW': '115', 'ATTND': '15', 'Exam': '55'},
 'Math': {'Quiz': '140', 'HW': '160', 'ATTND': '20', 'Exam': '40'}
  ]}}

I can construct the dictionary itself, but where I am having issues is how to set the values programmatically. how do I index into the list inside the dictionary and set the value like that programmatically if I just have a list of values as written above?

cvp

@multitech_news I guess that with

{'Abraham': {'subjects': ['Chem': {'Quiz':....

You mean

{'Abraham': {'subjects': {'Chem': {'Quiz':....
ccc

GitHub Co-pilot wrote:

d = {
    "Abraham": {
        "subjects": {
            "Chem": {"Quiz": "127", "HW": "135", "ATTND": "17", "Exam": "46"},
            "Bio": {"Quiz": "154", "HW": "64", "ATTND": "14", "Exam": "54"},
            "Phy": {"Quiz": "115", "HW": "115", "ATTND": "15", "Exam": "55"},
            "Math": {"Quiz": "140", "HW": "160", "ATTND": "20", "Exam": "40"},
        }
    }
}

for student in d:
    for subject in d[student]["subjects"]:
        for item in d[student]["subjects"][subject]:
            print(item, d[student]["subjects"][subject][item])
            d[student]["subjects"][subject][item] = 8
cvp

@ccc I guess he wants to avoid typing several times the same texts like the access_types and subjects

ccc
for subject in chem, bio, phy, math:
    print({key: value for key, value in zip(assess_type, subject)})

{'Quiz': '127', 'HW': '135', 'ATTND': '17', 'Exam': '46'}
{'Quiz': '154', 'HW': '64', 'ATTND': '14', 'Exam': '54'}
{'Quiz': '115', 'HW': '115', 'ATTND': '15', 'Exam': '55'}
{'Quiz': '140', 'HW': '160', 'ATTND': '20', 'Exam': '40'}