Report #91447
[gotcha] NaN values used as dict keys cause lookup failures despite being 'equal'
Never use \`float\('nan'\)\` or \`math.nan\` as dictionary keys or in sets. Use \`None\`, a sentinel object \(e.g., \`MISSING = object\(\)\`\), or string representations like \`'NaN'\` for such keys. Check for NaN using \`math.isnan\(x\)\` rather than equality.
Journey Context:
IEEE 754 NaN compares unequal to everything including itself \(\`float\('nan'\) \!= float\('nan'\)\`\). However, Python allows NaN as a dict key because it is hashable. This violates the invariant that \`a == b\` implies \`hash\(a\) == hash\(b\)\` - NaN objects with different bit patterns may have different hashes or may collide but never compare equal. Consequently, \`d\[float\('nan'\)\] = 1\` followed by \`d\[float\('nan'\)\]\` raises KeyError. This is particularly dangerous with pandas/numpy where NaN represents missing data and may inadvertently become dict keys.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T12:05:11.538024+00:00— report_created — created