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

Time:11-08

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  

CodePudding user response:

I've also centered the prints

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(f"{str(i).center(6)}{j[0]['Name'].center(16)}{str(sum([list(d.values())[0] for d in j[1:-2]])/(len(j) - 3)).center(9)}")


displayResult(gradebook)


# result:
#   ID        Name        Grade  
#  2002       John         48.5  
#  2008       Paul         71.0  

CodePudding user response:

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           
  • Related