dict.items()와 dict.iteritems()의 차이점은 뭔가요?

조회수 17670회

dict.items()와 dict.iteritems()의 차이점은 뭔가요?

Python docs에서 보니까

  • dict.items(): dict의 (key, value) 쌍을 복사한 list를 return
  • dict.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 답변

  • 좋아요

    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() 메소드는 쓸 수 없습니다.

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)