Question

Note, using Python 2.4. Here is a dictionary I have called d_ourbook:

 {'130405C00465000': [[8.6999999999999993, 8.9000000000000004, 0.50749999999999995, 32.810000000000002, -141.1575]]}

The value is a list of floats. I am trying to make a function that displays the same dictionary, but with values limited to two floating points.

I made a floating point --> 2decimal string function called two(floatnum):

def two(floatnum):
    return '%.2f' %(floatnum)

My function to loop or zip through the dictionary and convert all the values to two(value) have been a nightmare and returns float argument required:

Traceback (most recent call last):
  File "esecombo.py", line 496, in ?
    print ' -- dt: ', dt(d_ourbook)
  File "esecombo.py", line 23, in dt
    new_d_name = dict(zip(d_name.keys(), [two(value)for value in d_name.values()]))
  File "esecombo.py", line 10, in two
    return '%.2f' %(floatnum)
TypeError: float argument required

Any help would be a lifesaver.

Était-ce utile?

La solution

Assuming that d_name is the dictionary you provided, then d_name.values() is a list of lists of lists of floats. So value is a list of lists of floats and you cannot hand that to two() without an error.

Even if you get that resolved the zip returns a number of tuples base on the shortest argument. So that:

new_d_name = dict(zip(d_name.keys(), 
                      [two(value) for value in (d_name.values()[0][0])]))

results in {'130405C00465000': '8.70'}

This assumes that all values are of the single item list in list type as in the example, in that case you probably could use:

new_d_name = dict(zip(d_name.keys(), 
                      [[two(value) for value in (d_name.values()[0][0])]]))

to get:

{'130405C00465000': ['8.70', '8.90', '0.51', '32.81', '-141.16']}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top