Why adding multiple 'nan' in python dictionary giving multiple entries?

前端 未结 3 1689
既然无缘
既然无缘 2021-01-18 11:23

Example problem:

import numpy as np
dc = dict()
dc[np.float(\'nan\')] = 100
dc[np.float(\'nan\')] = 200

It is creating multiple entries for

3条回答
  •  梦谈多话
    2021-01-18 11:40

    As was mentioned in a comment to you, nan is never "equal" to another nan, do your dict is writing a new key for it. This is the behavior for nan values in most languages, not just python.

    I would suggest not using it as a key at all, or at least explain the purpose of it so we can find better ways to achieve that purpose without falling into pitfalls like this.

    In your case you could test this bahavior for yourself:

    a=list(dc.keys())
    print(a[0]==a[1]) # will output False
    

    The output for the above code (False) means that for the system, the are in fact different keys that do not clash

提交回复
热议问题