python type_error ai_generated true

TypeError: 不可哈希的类型: 'dict'

TypeError: unhashable type: 'dict'

ID: python/unittest-testcase-assertcountequal-unhashable

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
0证据数
2024-11-05首次发现

版本兼容性

版本状态引入弃用备注
3.10 active
3.11 active
3.12 active

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 70% 失败

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

  2. 75% 失败

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