我一直尝试使用 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()
anddict.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/