Round off dict values to 2 decimals

前端 未结 6 1727
庸人自扰
庸人自扰 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条回答
  •  有刺的猬
    2021-01-16 11:52

    Answering the second part of your question

    Try replacing line 5 of your code with:

     v = round(v, 2)
    

    This will round the number to two decimal places. Using round, I get

    [{'a': 80.0, 'c': 10.0, 'b': 0.08, 'd': 10.67}, {'a': 80.73, 'c': 10.78, 'b': 0.0, 'd': 10.0}, {'a': 80.72, 'c': 10.0, 'b': 0.78, 'd': 10.0}, {'a': 80.78, 'c': 10.0, 'b': 0.0, 'd': 10.98}]
    

    I am using Python 2.7.2. Here's all the code:

    from math import ceil 
    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)
                #print v
                d[k] = v
        return
    
    roundingVals_toTwoDeci(y)
    s = json.dumps(y)
    print s
    

提交回复
热议问题