• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

10:26 popitem() 질문입니다

24.04.24 18:43 작성 조회수 43

0

 argument가 필요한 pop(arg)와 달리 popitem()는 변수 없이 무작위로 key 하나를 pop 한다고 하셨는데요. 아무리 돌려봐도 무작위가 아니라 맨 마지막에 선언한 key부터 차례대로 pop 하는 것 같습니다.

 

dictionary는 순서가 없는 자료형이라 key 간 순서가 있는 것 같진 않은데 제일 마지막에 선언한 key부터 pop되는게 맞나요?

 

코드 아래 첨부드립니다.-----------

 

# Chapter03-5 # Python Dictionary # 범용적으로 가장 많이 사용 # 순서x, 키 중복x, 수정o, 삭제 o # 선언. 중괄호 사용 a = {'name': 'Kim', 'phone': '01033337777', 'birth':'870514'} # 중괄호 + 키 + : + 값. 키는 int등 다른 자료형도 가능 b = {0: 'Hello Phtyon'} # 키는 숫자도 가능 c = {'arr': [1, 2, 3, 4]} # 값 역시 리스트 등 어떤 자료형도 가능 d = { 'Name' : 'Niceman', 'City' : 'Seoul', 'Age' : 33, 'Grade':'A', 'Status': True } # 가독성 좋게 보통 이렇게 많이 선언함. e = dict([ ('Name', 'Niceman'), ('City', 'Seoul'), ('Age', 33), ('Grade', 'A'), ('Status',True) ]) # 사실 이게 가장 정석임. dict 명령어 안에 list 안에 튜플. 어려워서 많이 쓰진 않지만 정석코드 선호하는 사람은 씀 f = dict( Name = 'Niceman', City = 'Seoul', Age = 33, Grade = 'A', Status = True ) # e의 개선형. 이걸 d와 더불어 가장 많이 사용함. 이거로 선언하는 습관 들이는게 좋음. print('a - ', type(a), a) print('b - ', type(b), b) print('c - ', type(c), c) print('d - ', type(d), d) print('e - ', type(e), e) print('f - ', type(f), f) print('>>>>>>') # 출력 print('a - ', a['name']) # 직접 key로 접근. 존재하지 않는 key를 가져오려하면 error print('a - ', a.get('name1')) # get 명령어로 접근. key로 접근하는 방식과 달리, 없는 key도 None으로 가져오므로 안정적. 많이 씀. print('b - ', b[0]) print('b - ', b.get(0)) print('f - ', f.get('City')) print('f - ', f.get('Age')) print('>>>>>') # 추가 a['address'] = 'seoul' print(a.get('address')) print(a['address']) a['rank'] = [1, 2, 3] print(a) print(len(a)) # key의 갯수 print(len(b)) print('>>>>') # 함수 : dict_keys, dict_values, dict_items : 반복문에서 사용 가능 print('a - ', a.keys()) # value는 무관. key만 가져옴 print('a - keys list', list(a.keys())) # key를 list 형태로 반환 print('b - ', b.keys()) print('c - ', c.keys()) print() print('a - ', a.values()) # value만 반환 print('b - ', b.values()) print() print('a - ', a.items()) # key-value가 튜플 형태로 한쌍으로 묶여서 리스트로 반환. 정석대로 선언할 때처럼 key-value 튜플 형태로 반환되는거임. print('a - items list', list(a.items())) # list로 형변환 print() print('a - ', a.pop('name')) # pop : 꺼내서 반환 후 원래 리스트에서는 삭제 print('a - after pop', a) print('c - ', c.pop('arr')) print('c - after pop', c) # 빈 dict print() print('f - ', f.popitem()) # popitem : 이름 지정 안해도 자동으로 뒤부터? 랜덤으로? pop print('f - after popitem', f) print('f - ',f.popitem()) print('f - after popitem', f) print('f - ',f.popitem()) print('f - after popitem', f) print('a - ', a.popitem()) print('a - after popitem', a) print('a - ', a.popitem()) print('a - after popitem', a) print('a - ', a.popitem()) print('a - after popitem', a)

답변 1

답변을 작성해보세요.

0

안녕하세요. 좋은 질문 감사합니다.

현재 사용하시는 파이썬 버전에서는 마지막 값이 제거 되는 것이 맞습니다.

 

과거에는 공식 레퍼런스를 보시면 버전에 따라서 랜덤 아이템 또는 마지막 아이템이 제거 되는 함수 입니다.

그래서 버전에 따라 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

 

감사합니다.