Home > front end >  How to decrease nested dictionary values
How to decrease nested dictionary values

Time:10-17

I have a nested dictionary like this:

class_grade = {
'classA': {'Andi':89, 'Budi':87, 'Caca':76, 'Dodi':74},
'classB': {'Ega':67, 'Fani':97, 'Gani':96, 'Hani':78},
'classC': {'Ida':87, 'Joko':64, 'Keke':76, 'Lani':58},
'classD': {'Momo':68, 'Nani':67, 'Oga':76, 'Pina':65}}

I want to reduce each student's grade by 5, the code I wrote is like this:

class_grade ['classA']['Andi'] = class_grade ['classA']['Andi'] - 5
class_grade ['classA']['Budi'] = class_grade ['classA']['Budi'] - 5

But it's very tiring to change them one by one, so how can I reduce each student's grade at once? Thanks

CodePudding user response:

If I understand you correctly, you can use a nested dictionary comprehension:

{key : {k : v - 5 for k, v in value.items()} 
 for key, value in class_grade.items()}
Out[585]: 
{'classA': {'Andi': 84, 'Budi': 82, 'Caca': 71, 'Dodi': 69},
 'classB': {'Ega': 62, 'Fani': 92, 'Gani': 91, 'Hani': 73},
 'classC': {'Ida': 82, 'Joko': 59, 'Keke': 71, 'Lani': 53},
 'classD': {'Momo': 63, 'Nani': 62, 'Oga': 71, 'Pina': 60}}

CodePudding user response:

You can do your job also using Pandas:

The necessary import is:

import pandas as pd

Start from conversion of your nested dictionary into a pandasonic DataFrame:

grades = pd.DataFrame.from_dict(class_grade)

Then you can subtract your value in one go:

res = grades - 5

The next step is to define a function to be applied to each column of res:

def colConv(col):
    return col.dropna().astype(int).to_dict()

Then apply this function to res:

wrk = res.apply(colConv)

So far, the index is composed of consecutive integers, so you should replace it with original column names:

wrk.index = grades.columns

And the last step is to convert wrk to a dictionary and save it back under class_grade:

class_grade = wrk.to_dict()

The result is:

{'classA': {'Andi': 84, 'Budi': 82, 'Caca': 71, 'Dodi': 69},
 'classB': {'Ega': 62, 'Fani': 92, 'Gani': 91, 'Hani': 73},
 'classC': {'Ida': 82, 'Joko': 59, 'Keke': 71, 'Lani': 53},
 'classD': {'Momo': 63, 'Nani': 62, 'Oga': 71, 'Pina': 60}}
  • Related