Alex Man
Alex Man

Reputation: 477

Check if a float number is in a dictionary key in Python

I have a dict like this tmp_dic = {'0.0': 'val0', '1': 'val1', 'key3': 'val2'} . Now during parsing a file, I wanna check if for instance a float value of lets say 1.0 is in tmp_dic keys or not? I have a simple logic like this, but seems it can return wrong answer sometimes.

str(int(1.0)) in tmp_dic.keys()

Do I need to check if numeric string is integer or float before checking if they exists in the keys? Thanks for the hints.

Upvotes: 3

Views: 954

Answers (1)

kederrac
kederrac

Reputation: 17322

you can use:

def gen_float(l):
    for f in l:
        try:
            yield float(f)
        except ValueError:
            pass
any(v == 1.00 for v in gen_float(tmp_dic.keys()))

output:

True

is better to cast your keys to float than converting your check float to an int than to a string, for ex. if your check float is 1.23 this will be converted to 1


or you can use:

1.0 in gen_float(tmp_dic.keys())

as @HeapOverflow was suggesting


it will be better if at tmp_dict creation time you will try to convert the keys into floats, than the search for a float in your dict will be O(1) time complexity


if you do not have strings like '1.0000' you can also use:

str(1.0) in tmp_dict or str(int(1.0)) in tmp_dict

Upvotes: 1

Related Questions