Home > Blockchain >  Best way to round a Dictionary key represented by a float in Python with a given precision
Best way to round a Dictionary key represented by a float in Python with a given precision

Time:03-06

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

CodePudding user response:

You are using the value at index 12 as key for the dictionary. You can round the value before passing it as the key.

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

To handle the segmentation you posted in the comments, with keys on event numbers in the thousandths decimal place, you need to do some math to generate the key.

Essentially, you have 5 bins between each hundredth decimal place to you need to round the values into. We can accomplish this by multiplying by 5, rounding, dividing by 5, and rounding again (to clip the value).

def nearest_even_1000th(x):
    return round(round(x * 5, 2) / 5, 3)

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

CodePudding user response:

You need the builtin function round

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