• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    해결됨

popitem() 의 사용에 대해서

19.08.20 04:53 작성 조회수 303

5

동영상 강의에 오류가 있는거 같습니다.

 

dict_a.popitem() 을 제가 실행했을 때는

몇 번이나 계속 실행해봐도 

해당 dict 의 가장 마지막요소를 반환하는데

영상에서는 "임의의 요소"를 반환한다고 하셨네요

 

제가 제대로 이해하고 있는게 맞는지 궁금합니다.

답변 3

·

답변을 작성해보세요.

4

안녕하세요. 우림님.
 
공식 레퍼런스를 보시면 버전에 따라서 랜덤 아이템 또는 마지막 아이템이 제거 되는 함수 입니다.
그래서 버전에 따라 random 함수하고 같이 사용 하는 경우가 많습니다.
 
Python Dictionary popitem() Method

The popitem() method removes the item that was last inserted into the dictionary. In versions before 3.7, the popitem() method removes a random item. The removed item is the return value of the popitem() method, as a tuple, see example below.

 

popitem()

Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order.

popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError.

Changed in version 3.7: LIFO order is now guaranteed. In prior versions, popitem() would return an arbitrary key/value pair.

 

 

버전별로 동작이 상이 하기 때문에 외국 포럼에서도 질문이 자주 등장합니다.

https://stackoverflow.com/questions/4809044/removing-items-randomly-from-a-dictionary

 

감사합니다.

3

박우림님의 프로필

박우림

질문자

2019.08.20

제가 사용하는 버젼이 3.7 이라서 그랬던 거군요

답변 감사합니다!!

0

alstjs0801님의 프로필

alstjs0801

2020.03.22

저도 같은 질문 하려고 했는데!!! 3.8.2 버전도 pop은 해당 dict의 가장 마지막 요소를 반환해서 궁금했습니다!