dict.items()和dict.iteritems()之间有什么适用的区别吗?

来自Python文档:

dict.items():返回字典的(键,值)对列表的副本。 dict.iteritems():返回字典(key, value)对上的迭代器。

如果我运行下面的代码,每一个似乎都返回一个对相同对象的引用。有没有什么细微的差别是我没有注意到的?

#!/usr/bin/python

d={1:'one',2:'two',3:'three'}
print 'd.items():'
for k,v in d.items():
   if d[k] is v: print '\tthey are the same object' 
   else: print '\tthey are different'

print 'd.iteritems():'   
for k,v in d.iteritems():
   if d[k] is v: print '\tthey are the same object' 
   else: print '\tthey are different'   

输出:

d.items():
    they are the same object
    they are the same object
    they are the same object
d.iteritems():
    they are the same object
    they are the same object
    they are the same object

当前回答

如果你有

{key1:value1, key2:value2, key3:value3,…}

在Python 2中,dict.items()复制每个元组并返回字典中的元组列表,即[(key1,value1), (key2,value2),…]。 含义是整个字典被复制到包含元组的新列表中

dict = {i: i * 2 for i in xrange(10000000)}  
# Slow and memory hungry.
for key, value in dict.items():
    print(key,":",value)

iteritems()返回字典项迭代器。返回项的值也是相同的,即(key1,value1), (key2,value2),…,但这不是一个清单。这只是一个字典项迭代器对象。这意味着更少的内存使用(减少50%)。

作为可变快照的列表:d.items() -> list(d.items()) 迭代器对象:d.t iteritems() -> iter(d.s ititems ())

元组是一样的。你比较了每个的元组,所以你得到相同的结果。

dict = {i: i * 2 for i in xrange(10000000)}  
# More memory efficient.
for key, value in dict.iteritems():
    print(key,":",value)

在Python 3中,dict.items()返回迭代器对象。Dict.iteritems()被移除,因此不再有问题。

其他回答

Dict.iteritems():提供一个迭代器。可以在循环之外的其他模式中使用迭代器。

student = {"name": "Daniel", "student_id": 2222}

for key,value in student.items():
    print(key,value)

('student_id', 2222)
('name', 'Daniel')

for key,value in student.iteritems():
    print(key,value)

('student_id', 2222)
('name', 'Daniel')

studentIterator = student.iteritems()

print(studentIterator.next())
('student_id', 2222)

print(studentIterator.next())
('name', 'Daniel')

Dict.items()返回一个二元组列表([(key, value), (key, value),…]),而dict.iteritems()是一个生成二元组的生成器。前者最初需要更多的空间和时间,但访问每个元素都很快,而后者最初需要更少的空间和时间,但生成每个元素需要更多的时间。

python 2中的Dict.iteritems()等价于python 3中的dict.items()。

字典iteritems在Python3中消失。因此使用iter(dict.items())来获得相同的输出和内存分配

如果你有

{key1:value1, key2:value2, key3:value3,…}

在Python 2中,dict.items()复制每个元组并返回字典中的元组列表,即[(key1,value1), (key2,value2),…]。 含义是整个字典被复制到包含元组的新列表中

dict = {i: i * 2 for i in xrange(10000000)}  
# Slow and memory hungry.
for key, value in dict.items():
    print(key,":",value)

iteritems()返回字典项迭代器。返回项的值也是相同的,即(key1,value1), (key2,value2),…,但这不是一个清单。这只是一个字典项迭代器对象。这意味着更少的内存使用(减少50%)。

作为可变快照的列表:d.items() -> list(d.items()) 迭代器对象:d.t iteritems() -> iter(d.s ititems ())

元组是一样的。你比较了每个的元组,所以你得到相同的结果。

dict = {i: i * 2 for i in xrange(10000000)}  
# More memory efficient.
for key, value in dict.iteritems():
    print(key,":",value)

在Python 3中,dict.items()返回迭代器对象。Dict.iteritems()被移除,因此不再有问题。