dict.viewkeys() 返回的数据类型是什么?[蟒蛇2.7] [英] What's the data type returned by dict.viewkeys()? [ python 2.7 ]
问题描述
我今天正在研究dict.viewkeys()
,发现我的python 称它为dict_keys
对象.我可以将其作为可迭代对象处理,但它不是生成器,因为我可以对其进行多次迭代.
以我有限的知识,我只知道几种数据类型,例如 String、int、float、list、dict、tuple、set.
但是昨天我了解到 enumerate()
返回一对特殊的数据,dict()
只能使用该数据对一次,因此它是一个特殊的元组生成器,带有 <代码>(index_of_iteration, item) 值
这个 dict_keys
对象是另一种我不知道它到底是什么,但我知道如何使用它"类型的 Python 对象?
它返回一个字典视图对象 (https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects).
这是字典中元素的动态视图.即,如果您查看字典中的键,如果您从字典中删除一个键,它也会从视图中删除.请参阅下面的示例.
来自文档:
<预><代码>>>>菜肴 = {'鸡蛋':2,'香肠':1,'培根':1,'垃圾邮件':500}>>>键 = 菜肴.viewkeys()>>>值 = 菜肴.viewvalues()>>># 迭代>>>n = 0>>>对于 val 值:... n += val>>>打印(n)504>>># 键和值以相同的顺序迭代>>>列表(键)['鸡蛋'、'培根'、'香肠'、'垃圾邮件']>>>列表(值)[2, 1, 1, 500]>>># 视图对象是动态的并反映字典的变化>>>德尔菜肴['鸡蛋']>>>del 菜肴['香肠']>>>列表(键)['垃圾邮件','培根']>>># 设置操作>>>钥匙&{'鸡蛋'、'培根'、'沙拉'}{'培根'}I am studying dict.viewkeys()
today, I found that my python calls it dict_keys
object. And I can deal it as an iterable, but it's not a generator, because I can iterate over it more than once.
By my limited knowledge, I know only a few data types such as String, int, float, list, dict, tuple, set.
But yesterday I learned that enumerate()
returns a special pair of data which can be used by dict()
only once, thus it's a special tuple generator with (index_of_iteration, item)
value
Is this dict_keys
object another "I don't know what it exactly is but I know how to use it" type of object in python, or something else?
It returns a dictionary view object (https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects).
This is a dynamic view of the elements in a dictionary. i.e. if you have a view to the keys in a dictionary, if you delete a key from the dictionary it will also be deleted from the view. See the examples below.
From the docs:
>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>> keys = dishes.viewkeys()
>>> values = dishes.viewvalues()
>>> # iteration
>>> n = 0
>>> for val in values:
... n += val
>>> print(n)
504
>>> # keys and values are iterated over in the same order
>>> list(keys)
['eggs', 'bacon', 'sausage', 'spam']
>>> list(values)
[2, 1, 1, 500]
>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['spam', 'bacon']
>>> # set operations
>>> keys & {'eggs', 'bacon', 'salad'}
{'bacon'}
Also see: What are Python dictionary view objects?
这篇关于dict.viewkeys() 返回的数据类型是什么?[蟒蛇2.7]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!