Programing

dict.items ()와 dict.iteritems ()의 차이점은 무엇입니까?

lottogame 2020. 10. 2. 21:21
반응형

dict.items ()와 dict.iteritems ()의 차이점은 무엇입니까?


dict.items()사이에 적용 가능한 차이점이 dict.iteritems()있습니까?

Python 문서에서 :

dict.items(): 사전의 (키, 값) 쌍 목록의 복사본반환합니다 .

dict.iteritems(): 사전의 (키, 값) 쌍에 대한 반복자반환합니다 .

아래 코드를 실행하면 각각 동일한 객체에 대한 참조를 반환하는 것 같습니다. 내가 놓친 미묘한 차이가 있습니까?

#!/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

그것은 진화의 일부입니다.

원래 Python items()은 실제 튜플 목록을 작성하여 반환했습니다. 잠재적으로 많은 추가 메모리가 필요할 수 있습니다.

그런 다음 생성기가 일반적으로 언어에 도입되었으며 해당 메서드는 .NET이라는 반복자 생성기 메서드로 다시 구현되었습니다 iteritems(). 원본은 이전 버전과의 호환성을 위해 남아 있습니다.

Python 3의 변경 사항 중 하나는 items()이제 반복자를 반환하고 목록이 완전히 빌드되지 않는다는 것입니다. iteritems()방법은 또한 이후, 사라 items()세 작품처럼 파이썬으로 viewitems()파이썬 2.7.


dict.items()2- 튜플 ( [(key, value), (key, value), ...]) 의 목록을 반환하는 반면는 2- 튜플 dict.iteritems()을 생성하는 생성기입니다. 전자는 처음에는 더 많은 공간과 시간이 필요하지만 각 요소에 액세스하는 것은 빠르지 만 두 번째는 처음에는 공간과 시간이 덜 걸리지 만 각 요소를 생성하는 데 약간 더 많은 시간이 걸립니다.


Py2.x에서

명령은 dict.items(), dict.keys()dict.values()반환 사본 사전의의 목록(k, v)쌍, 키와 값을. 복사 된 목록이 매우 크면 많은 메모리가 필요할 수 있습니다.

명령 dict.iteritems(), dict.iterkeys()dict.itervalues()반환 반복자 사전의 이상 (k, v)쌍, 키와 값을.

명령 dict.viewitems(), dict.viewkeys()dict.viewvalues()반환 뷰 객체 사전의 변경 사항을 반영 할 수 있습니다. (즉 , 사전에 del항목을 추가하거나 (k,v)쌍을 추가 하면보기 개체가 동시에 자동으로 변경 될 수 있습니다 .)

$ python2.7

>>> d = {'one':1, 'two':2}
>>> type(d.items())
<type 'list'>
>>> type(d.keys())
<type 'list'>
>>> 
>>> 
>>> type(d.iteritems())
<type 'dictionary-itemiterator'>
>>> type(d.iterkeys())
<type 'dictionary-keyiterator'>
>>> 
>>> 
>>> type(d.viewitems())
<type 'dict_items'>
>>> type(d.viewkeys())
<type 'dict_keys'>

Py3.x에서

In Py3.x, things are more clean, since there are only dict.items(), dict.keys() and dict.values() available, which return the view objects just as dict.viewitems() in Py2.x did.

But

Just as @lvc noted, view object isn't the same as iterator, so if you want to return an iterator in Py3.x, you could use iter(dictview) :

$ python3.3

>>> d = {'one':'1', 'two':'2'}
>>> type(d.items())
<class 'dict_items'>
>>>
>>> type(d.keys())
<class 'dict_keys'>
>>>
>>>
>>> ii = iter(d.items())
>>> type(ii)
<class 'dict_itemiterator'>
>>>
>>> ik = iter(d.keys())
>>> type(ik)
<class 'dict_keyiterator'>

You asked: 'Are there any applicable differences between dict.items() and dict.iteritems()'

This may help (for Python 2.x):

>>> d={1:'one',2:'two',3:'three'}
>>> type(d.items())
<type 'list'>
>>> type(d.iteritems())
<type 'dictionary-itemiterator'>

You can see that d.items() returns a list of tuples of the key, value pairs and d.iteritems() returns a dictionary-itemiterator.

As a list, d.items() is slice-able:

>>> l1=d.items()[0]
>>> l1
(1, 'one')   # an unordered value!

But would not have an __iter__ method:

>>> next(d.items())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list object is not an iterator

As an iterator, d.iteritems() is not slice-able:

>>> i1=d.iteritems()[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dictionary-itemiterator' object is not subscriptable

But does have __iter__:

>>> next(d.iteritems())
(1, 'one')               # an unordered value!

So the items themselves are same -- the container delivering the items are different. One is a list, the other an iterator (depending on the Python version...)

So the applicable differences between dict.items() and dict.iteritems() are the same as the applicable differences between a list and an iterator.


dict.items() return list of tuples, and dict.iteritems() return iterator object of tuple in dictionary as (key,value). The tuples are the same, but container is different.

dict.items() basically copies all dictionary into list. Try using following code to compare the execution times of the dict.items() and dict.iteritems(). You will see the difference.

import timeit

d = {i:i*2 for i in xrange(10000000)}  
start = timeit.default_timer() #more memory intensive
for key,value in d.items():
    tmp = key + value #do something like print
t1 = timeit.default_timer() - start

start = timeit.default_timer()
for key,value in d.iteritems(): #less memory intensive
    tmp = key + value
t2 = timeit.default_timer() - start

Output in my machine:

Time with d.items(): 9.04773592949
Time with d.iteritems(): 2.17707300186

This clearly shows that dictionary.iteritems() is much more efficient.


If you have

dict = {key1:value1, key2:value2, key3:value3,...}

In Python 2, dict.items() copies each tuples and returns the list of tuples in dictionary i.e. [(key1,value1), (key2,value2), ...]. Implications are that the whole dictionary is copied to new list containing tuples

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

dict.iteritems() returns the dictionary item iterator. The value of the item returned is also the same i.e. (key1,value1), (key2,value2), ..., but this is not a list. This is only dictionary item iterator object. That means less memory usage (50% less).

  • Lists as mutable snapshots: d.items() -> list(d.items())
  • Iterator objects: d.iteritems() -> iter(d.items())

The tuples are the same. You compared tuples in each so you get same.

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

In Python 3, dict.items() returns iterator object. dict.iteritems() is removed so there is no more issue.


dict.iteritems(): gives you an iterator. You may use the iterator in other patterns outside of the loop.

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')

If you want a way to iterate the item pairs of a dictionary that works with both Python 2 and 3, try something like this:

DICT_ITER_ITEMS = (lambda d: d.iteritems()) if hasattr(dict, 'iteritems') else (lambda d: iter(d.items()))

Use it like this:

for key, value in DICT_ITER_ITEMS(myDict):
    # Do something with 'key' and/or 'value'.

dict.iteritems is gone in Python3.x So use iter(dict.iitems()) to get the same output and memory alocation


dict.iteritems() in python 2 is equivalent to dict.items() in python 3.

참고URL : https://stackoverflow.com/questions/10458437/what-is-the-difference-between-dict-items-and-dict-iteritems

반응형