'Best way to round a Dictionary key represented by a float in Python with a given precision

I have a list of lists like

firstlist = [[x1,12.0,text,0.05],[x2,12.0,text,0.08],[x3,14.0,text,0.05],[x4,16.0,text,0.05],[x5,12.0,text,0.08]]

I tried to create a dictionary like

mydict = {0.05:[[x1,12.0,text,0.05],[x3,14.0,text,0.05],[x4,16.0,text,0.05]],
          0.08:[[x2,12.0,text,0.08],[x5,12.0,text,0.08]]}


d = {}
for row in FirstList[1:]:
    # Add name to dict if not exists
    if len(row)==13:
        if row[12] not in d:
            d[row[12]] = []
            # Add all non-Name attributes as a new list
        d[row[12]].append(row[1:])

where keys represent commissions.

My problem is that some commissions are very close resulting more rows.

for example

 mydict = {0.05:[[x1,12.0,text,0.05],[x3,14.0,text,0.05],[x4,16.0,text,0.05]],
           0.048:[[x2,12.0,text,0.048],[x5,12.0,text,0.048]],
           0.051:[[x2,12.0,text,0.051],[x5,12.0,text,0.051]]}

how to have the keys for example if keys are 0.049 or 0.051 with a difference of 0.01-0.02 and close to 0.050 to be 0.05



Solution 1:[1]

You need the builtin function round

round(0.05, 2)  # 0.05
round(0.048, 2) # 0.05
round(0.051, 2) # 0.05

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nikhil Devadiga