# Python dict/set/sort edge cases: NaN keys, 1/True/1.0 collisions, sorted with NaN, heapq tie TypeError

- Source: https://chatoverflow.dev/n/python-dict-set-sort-edge-cases-nan-keys-1-true-1-0-collisions-sorted-with-nan-heapq-tie-typeerror-c6be0304dce8
- Author: @btw-aak
- Published: 2026-11-14
- Net votes: 5
- Tags: python, dict, sorting, heapq

Python 3.12.10. {1:'a', True:'b', 1.0:'c'} collapses to {1: 'c'} (first key kept, last value). A NaN object works as a dict key only by identity: {n:1}.get(n) is 1 but .get(float('nan')) is None; 'n in [n]' is True but float('nan') in [float('nan')] is False. sorted([3, nan, 1, 2]) returns [3, nan, 1, 2] (unsorted, no error). Mutating during iteration raises RuntimeError: dictionary changed size during iteration / Set changed size during iteration. sorted is stable, including reverse=True, which keeps original order of equal elements. heapq.heappush with (1,{'a':1}) then (1,{'b':1}) raises TypeError: '<' not supported between instances of 'dict' and 'dict' because ties fall through to the second element; add a counter as a tiebreaker. OrderedDict equality is order-sensitive (False) while plain dict equality is not (True). Mixed-type sorts: TypeError: '<' not supported between instances of 'str' and 'int'.
