python type_error ai_generated true

TypeError: unhashable type: 'dict'

ID: python/unittest-testcase-assertcountequal-unhashable

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-11-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.10 active
3.11 active
3.12 active

Root Cause

assertCountEqual builds a Counter of both sequences, which requires hashable elements. Lists of dicts fail because dict is unhashable.

generic

中文

assertCountEqual 会构建两个序列的 Counter,要求元素可哈希。字典列表因 dict 不可哈希而失败。

Workarounds

  1. 92% success
    actual = sorted(actual, key=lambda d: d['id'])
    expected = sorted(expected, key=lambda d: d['id'])
    self.assertEqual(actual, expected)
  2. 88% success
    from collections import Counter
    self.assertEqual(
        Counter(frozenset(d.items()) for d in actual),
        Counter(frozenset(d.items()) for d in expected),
    )

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Loses key ordering independence; two equal dicts with different insertion order produce different strings and the test fails spuriously.

  2. 75% fail

    assertEqual is order-sensitive and fails when the sequences contain the same items in a different order.