Home > Enterprise >  How to insert values into a nested dictionary from existing dictionary values
How to insert values into a nested dictionary from existing dictionary values

Time:10-28

I have a dictionary which is like a json format. Like below:-

dito1 ={'result2':[{'math':20,'science':22,'english':31},{'math':26,'science':27,'english':33},
                                    {'math':15,'science':55,'english':44}],'pet2':0,
                                    'result':[{'rt':66,'io':49,'op':10},{'rt':24,'io':25,'op':5}],'pet':20}

Now I want to create a new dictionary using the above values, the new dictionary has to be seen like below:-

{'type': 'etc', 'scores': [{'math': 20, 'science': 22, 'english': 31}, {'math': 26, 'science': 27, 'english': 33}, {'math': 15, 'science': 55, 'english': 44}], 'math total': 61,'scores2':[{'math': 66, 'science': 49, 'english': 10}, {'math': 24, 'science': 25, 'english': 5}],'math total':90}

In the first dictionary there are two keys result2, result that have scores information that are lists. By using this information they must be converted as above and the math total in the second dictionary is total marks of the math's in each list. I have tried to get the desired output but I am not able to divide them into two based on the keys they belong to. The code I have tried is as follows:-

dito1 ={'result2':[{'math':20,'science':22,'english':31},{'math':26,'science':27,'english':33},
                                    {'math':15,'science':55,'english':44}],'pet2':0,
                                    'result':[{'rt':66,'io':49,'op':10},{'rt':24,'io':25,'op':5}],'pet':20}
reslt=[]
math_total=[]
for key,value in dito1.items():
    if key == 'result' or key == 'result2':
        for i in value:
            for k,v in i.items():
                if k == 'math':
                    t=v
                if k == 'rt':
                    t=v
                if k == 'science':
                    r=v
                if k == 'io':
                    r=v
                if k=='op':
                    e=v
                if k=='english':
                    e=v
            rest ={'math':t,'science':r,'english':e}
            math_total.append(t)
            reslt.append(rest)

final_dict={'type':'etc','math total':reslt,'scores':sum(math_total)}
    
print(final_dict)

The output I got is:-

{'type': 'etc', 'scores': [{'math': 20, 'science': 22, 'english': 31}, {'math': 26, 'science': 27, 'english': 33}, {'math': 15, 'science': 55, 'english': 44}, {'math': 66, 'science': 49, 'english': 10}, {'math': 24, 'science': 25, 'english': 5}], 'math total': 151}

Excepted output:-

{'type': 'etc', 'scores': [{'math': 20, 'science': 22, 'english': 31}, {'math': 26, 'science': 27, 'english': 33}, {'math': 15, 'science': 55, 'english': 44}], 'math total': 61,'scores2':[{'math': 66, 'science': 49, 'english': 10}, {'math': 24, 'science': 25, 'english': 5}],'math total2':90}

CodePudding user response:

As an aside, I'd suggest re-thinking the structure/naming scheme of this final_dict; using keys like 'scores' and 'scores2' indicates you may want a list structure instead of a dict structure.

dito1 = {'result2': [{'math': 20, 'science': 22, 'english': 31}, {'math': 26, 'science': 27, 'english': 33}, {'math': 15, 'science': 55, 'english': 44}], 'pet2': 0, 'result': [{'rt': 66, 'io': 49, 'op': 10}, {'rt': 24, 'io': 25, 'op': 5}], 'pet': 20}

translate = {'rt':'math','io':'science','op':'english'}

final_dict = {'type':'etc'}
for key,list_of_dict in dito1.items():
    if key in ['result', 'result2']:
        score_key = key.replace('result','scores')
        final_dict[score_key] = []

        math_total_key = key.replace('result','math_total')
        final_dict[math_total_key] = 0
        for d in list_of_dict:
            # translate to the intended score names as needed
            for k in ['rt','io','op']:
                if k in d:
                    d[translate[k]] = d.pop(k)

            # append the scores to the appropriate nested dict
            final_dict[score_key].append(dict(d))
            # and increment the math_total for that set of scores
            final_dict[math_total_key]  = d['math']
print(final_dict)

results in

for key,value in final_dict.items():
    print(f'{key}: {value}')

# Output:
type: etc
scores2: [{'math': 20, 'science': 22, 'english': 31}, {'math': 26, 'science': 27, 'english': 33}, {'math': 15, 'science': 55, 'english': 44}]
math_total2: 61
scores: [{'math': 66, 'science': 49, 'english': 10}, {'math': 24, 'science': 25, 'english': 5}]
math_total: 90
  • Related