Float values as dictionary key

前端 未结 5 734
时光说笑
时光说笑 2020-11-27 21:30

I am developing a class for the analysis of microtiter plates. The samples are described in a separate file and the entries are used for an ordered dictionary. One of the ke

相关标签:
5条回答
  • 2020-11-27 22:04

    Another option would be to use tuples:

    dictionary = {(6.8,): 0.3985}
    dictionary[(6.8,)]
    

    Then Retrieving the values later for plotting is easily done with something like

    points = [(pH, value) for (pH,), value in dictionary.items()]
        ...
    
    0 讨论(0)
  • 2020-11-27 22:06

    Perhaps you want to truncate your float prior to using is as key?

    Maybe like this:

    a = 0.122334
    round(a, 4)       #<-- use this as your key?
    

    Your key is now:

    0.1223           # still a float, but you have control over its quality
    

    You can use it as follows:

    dictionary[round(a, 4)]   
    

    to retrieve your values

    0 讨论(0)
  • 2020-11-27 22:06

    Another way would be enter the keys as strings with the point rather than a p and then recast them as floats for plotting.

    Personally, if you don't insist on the dict format, I would store the data as a pandas dataframe with the pH as a column as these are easier to pass to plotting libraries

    0 讨论(0)
  • 2020-11-27 22:14

    There's no problem using floats as dict keys.

    Just round(n, 1) them to normalise them to your keyspace. eg.

    >>> hash(round(6.84, 1))
    3543446220
    >>> hash(round(6.75, 1))
    3543446220
    
    0 讨论(0)
  • 2020-11-27 22:18

    Another quick option is to use strings of the float

    a = 200.01234567890123456789
    b = {str(a): 1}
    for key in b:
        print(float(key), b[key])
    

    would print out

    (200.012345679, 1)
    

    notice a gets truncated at tenth digit after decimal point.

    0 讨论(0)
提交回复
热议问题