dictionary - dict.keys 不打印列表但打印 ListView 的问题

标签 dictionary python-3.x key

我一直尝试使用 dict.keys 从我的字典中获取键列表,但它一直给我:

def 反向(PB = {'l': 3, 'y':1, 'u':2}): 打印(PB.keys())

打印:

dict_keys(['u', 'l', 'y'])

在我使用 2.7 以上的 python 版本之前从未遇到过这个问题...有什么想法吗?

最佳答案

Python 3 返回 view objects :

The objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.

您可以将它们传递到 list() 中,将它们转换为列表(Python 2 行为):

>>> d = {'l': 3, 'y':1, 'u':2}
>>> d.keys()
dict_keys(['y', 'l', 'u'])
>>> list(d.keys())
['y', 'l', 'u']

另外,传递 mutable objects as default arguments 时要小心:

>>> def reverse(PB={'l': 3, 'y':1, 'u':2}):
...     PB['l'] += 4
...     
...     print(PB)
... 
>>> reverse()
{'y': 1, 'l': 7, 'u': 2}
>>> reverse()
{'y': 1, 'l': 11, 'u': 2}
>>> reverse()
{'y': 1, 'l': 15, 'u': 2}

我默认为None:

def reverse(PB=None):
    if PB is None:
        PB = {'l': 3, 'y':1, 'u':2}

关于dictionary - dict.keys 不打印列表但打印 ListView 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15445067/

相关文章:

python - 来自 pandas 数据框列的字典

python - 包含字典列表的字典

python - 与 mypy 比较的类型

c++ - 有没有办法在多映射内联中查找键的数量?

php - 从 PHP 中的数组中删除黑名单键

java - 在 Java 中使用就地集合初始化器的缺点是什么

python - 根据转换为整数后的值对字典键进行排序

Python排序列表设置

python-3.x - 在通过 pyenv 安装 python 3.7.0 期间 zlib 不可用,我该如何解决?

java - 使 if 语句 "fire"成为一个键