• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

자꾸 keyerror가 떠요

18.04.06 10:06 작성 조회수 3.42k

0

def value_to_key(dict):

dict_items = dict.items()

list_value = list(dict.values())

list_key = list(dict.keys())

i = 0

dict_2 = {}

while i < len(list_key):

dict_2[list_value[i]] = list_key[i]

i += 1

user_input = input("input the key : ")

return dict_2[user_input]

-----------------------------------------------(여기까지가 함수 식)

dict = {"America":1, "China":2, "Korea":3, "Japan":4}

value_to_key(dict)

제가 쓴 코드는 이건데 print(dict_2)하면 {1: 'America', 2: 'China', 3: 'Korea', 4: 'Japan'}로 나오는데

user_input = 3 일때,

====================================

Traceback (most recent call last):

File "valuekey.py", line 20, in

value_to_key(dict)

File "valuekey.py", line 17, in value_to_key

return dict_2[user_input]

KeyError: '3'

요런게 뜨네요 어디가 문제인지 모르겠습니다.

답변 1

답변을 작성해보세요.

0

3이 integer가 아니라서 그렇습니다.