字典和集合

  • 字典推导式: `{c: x for c, x in lst}
  • 拆包: **dict
>>> {'a': 0, **{'x': 1}, 'y': 2, **{'z': 3, 'x': 4}} 
{'a': 0, 'x': 4, 'y': 2, 'z': 3}
  • 合并映射(Merging Mappings): |, |=, d1 | d2
  • match/case: 模式匹配,模式中key的顺序无关紧要
  • 可哈希

    An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare equal must have the same hash value. Most of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not; immutable containers (such as tuples and frozensets) are only hashable if their elements are hashable. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their id().

  • With Python’s fail-fast philosophy, dict access with d[k] raises an error when k is not an existing key
    • 可以替换d[k]d.get(k, default)
    • 使用defaultdict代替dict
    • 实现__missing__
  • 集合:…