如何减少字典并同时用数值进行计算?

时间:2017-09-09 02:02:45

标签: python

我想转换这本词典:

d1 = {'course ': 'python', 'LastGPA' : 90, 'CurrentGPA': 80}

进入这个:

d1 = {'course ': 'python', 'LastGPA+CurrentGPA' : (90+80)/2}

这是Python中最后两个数字的平均值。

1 个答案:

答案 0 :(得分:0)

我做了以下方式

def new_dic(d1):
    x=[]
    y=[]
    x1=[]
    for item in d1:
        x.append(item)
        y.append(d1[item])

    for value in y:
        try:
            x1.append(int(value))
        except ValueError:
            continue
    x2 = x[-2]+'+'+x[-1]
    d1.update({x2:sum(x1)/len(x1)})
    d1.pop(x[-2])
    d1.pop(x[-1])
    print(d1)

new_dic(d1)