Skip to main content
 首页 » 编程设计

python之为什么 python dict 键/值不像鸭子一样嘎嘎叫

2025年05月04日11java哥

Python 是 duck typed ,通常这可以避免在处理原始对象时强制转换 faff。

The canonical example (and the reason behind the name) is the duck test: If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.

然而,一个值得注意的异常(exception)是字典键/值,它看起来像鸭子并且像鸭子一样游泳,但值得注意的是不会像鸭子一样嘎嘎。

>>> ls = ['hello'] 
>>> d = {'foo': 'bar'} 
>>> for key in d.keys(): 
..      print(key) 
.. 
'foo' 
>>> ls + d.keys() 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: can only concatenate list (not "dict_keys") to list 

谁能告诉我这是为什么?

请您参考如下方法:

字典键实际上实现了集合的接口(interface)而不是列表的接口(interface),因此您可以直接对其他集合执行字典键的集合操作:

d.keys() & {'foo', 'bar'} # returns {'foo'} 

但它没有实现__getitem__、__setitem__、__delitem__、insert方法,这些方法是需要像列表一样“嘎嘎”,因此如果不先显式转换为列表,它就无法执行任何列表操作:

ls + list(d.keys()) # returns ['hello', 'foo']