dict.items()와 dict.iteritems()의 차이점은 뭔가요?
조회수 17727회
dict.items()와 dict.iteritems()의 차이점은 뭔가요?
Python docs에서 보니까
dict.items()
: dict의 (key, value) 쌍을 복사한 list를 returndict.iteritems()
: dict의 (key, value) 쌍의 iterator를 return
라고 하던데, 제가 코드를 돌려 보니까 둘 이 같은 객체의 레퍼런스를 return하던데 제가 빼먹은 게 있나요?
소스코드
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'
Output:
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
1 답변
-
dict.items() 와 dict.iteritems()는 파이썬 버전에 따라 다른 결과를 냅니다.
원래 파이썬
items()
는 tuple을 원소로 가지는list
를 return 했습니다. 이 방법은 메모리가 많이 필요했기 때문에, generator가 도입된 후 메모리의 효율적 관리를 위해items()
대신 iterator-generator 메소드인iteritems()
를 쓰게 됩니다.다만 2.x에서는 구버전과의 호환성을 위해서
items()
와iteritems()
를 모두 지원했지만 python3에서는iterm()
은 list가 아닌 iterator를 return하고(python3 의items()
= python2의iteritems()
)iteritems()
메소드는 쓸 수 없습니다.
댓글 입력