Round off dict values to 2 decimals

前端 未结 6 1740
庸人自扰
庸人自扰 2021-01-16 11:29

I\'m having a hard time rounding off values in dicts. What I have is a list of dicts like this:

y = [{\'a\': 80.0, \'b\': 0.0786235, \'c\': 10.0, \'d\': 10.6         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-16 12:00

    import json
    
    
    y = [{'a': 80.0, 'b': 0.0786235, 'c': 10.0, 'd': 10.6742903}, {'a': 80.73246, 'b': 0.0, 'c':   
    10.780323, 'd': 10.0}, {'a': 80.7239, 'b': 0.7823640, 'c': 10.0, 'd': 10.0}, {'a': 
    80.7802313217234, 'b': 0.0, 'c': 10.0, 'd': 10.9762304}]
    
    def roundingVals_toTwoDeci(y):
    
        for d in y:
            for k, v in d.items():
                v = round(v,2) # <--- round() does exact that.
                d[k] = v # <--- You need to put the rounded v back in d
                print v
        return
    
    roundingVals_toTwoDeci(y)
    s = json.dumps(y)
    print s
    

提交回复
热议问题