Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate Average and add new key:value pairs to an existing dictionary

I need to find the average for the scores M1 and E1 for every name in the list and want to add another key: value pair called average : (M1+E1)/2. How do i add more key: value pairs under 2002 and 2008 ?

gradebook = {
    2002: [
        {"Name" : "John"},
        {"M1" : 87},
        {"E1" : 10},
        {"Score" : 90},
        {"Grade" : "A"}
        ],
    2008 : [
        {"Name" : "Paul"},
        {"M1" : 83},
        {"E1" : 59},
        {"Score" : 77},
        {"Grade" : "C"}
        ],
}
def displayResult(gradebook):
    print('ID       Name        Grade')
    for i,j in gradebook.items():
        print('{}       {}       {}'.format(i,j[0]['Name'],j[4]['Grade']))
    
    
displayResult(gradebook)


Current output

|ID       Name        Grade
|2002       John       A
|2008       Paul       C

Expected
ID       Name        Average
2002       John       48.5
2008       Paul       71  

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I suggest to slightly modify the structure of gradebook before passing it to the displayResult() function:

gradebook = {
    2002: [
        {"Name": "John"},
        {"M1": 87},
        {"E1": 10},
        {"Score": 90},
        {"Grade": "A"},
    ],
    2008: [
        {"Name": "Paul"},
        {"M1": 83},
        {"E1": 59},
        {"Score": 77},
        {"Grade": "C"},
    ],
}


def displayResult(gradebook):
    fmt_string = "{:<15}{:<15}{:<15}"

    print(fmt_string.format("ID", "Name", "Grade"))
    for i, j in gradebook.items():
        print(
            fmt_string.format(
                i, j["Name"], (j.get("M1", 0) + j.get("E1", 0)) / 2
            )
        )


tmp = {}
for k, v in gradebook.items():
    tmp[k] = {kk: vv for d in v for kk, vv in d.items()}

# print(tmp)

# `tmp` is now:
# {
#     2002: {"Name": "John", "M1": 87, "E1": 10, "Score": 90, "Grade": "A"},
#     2008: {"Name": "Paul", "M1": 83, "E1": 59, "Score": 77, "Grade": "C"},
# }

displayResult(tmp)

Prints:

ID             Name           Grade          
2002           John           48.5           
2008           Paul           71.0           
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading