1. Dict 객체의 Key와 Value 값
Dictionary 객체는 Key 값으로 Value에 접근할 수 있지만,
Value 값으로 Key 값에 단순하게 접근할 방법은 없다.
반면 List 객체와 같은 Sequence 객체들은 index로 각 항목에 접근할 수도 있고,
각 항목으로 index에 접근할 수도 있다.
프로젝트를 진행하면서 이 부분을 인지했고
Dict에서 Value로 Key에 접근할 수 있는 방법이 있을까 나중에 생각해 봐야겠다는 생각이 들었었다.
2. 구현 프로그램
Value와 Key를 뒤집은 결과를 반환하는 함수 invert_dict() 를 작성하기.
변환된 딕셔너리 객체의 Key 값의 Value는 list로 추가하기.
해당 Key 값의 Value가 여러 개일 경우 모든 항목이 list에 추가되도록 구현.
예시)
invert_dict({1: 'a', 2: 'b', 3: 'c'}) #=> {'a': [1], 'b': [2], 'c': [3]}
invert_dict({1: 'a', 2: 'b', 3: 'c', 4: 'c'}) #=> {'a': [1], 'b': [2], 'c': [3, 4]}
invert_dict({1: True, 2: False, 3: True}) #=> {True: [1, 2, 3], False: [2]}
3. 삽질한 코드
def invert_dict(my_dict):
keys = my_dict.keys() # 새로 value가 될 애들
values = my_dict.values() # 새로 key가 될 애들
inverted_items = list(zip(values, keys)) # 자리 바꿔서 짝(튜플) 지어주기
inverted_dict = {} # 빈 dict를 만들고
inverted_dict.update(inverted_items) #update 매서드를 통해 새로운 key, value 추가하기
return inverted_dict
처음 key와 value를 switch한다고 했을 때 바로 들었던 아이디어는 이런 방식이었다.
그런데 이렇게 코드를 짜면
- 같은 key를 가진 값들이 모두 추가되지 않고,
- value들이 리스트 형태로 구현되지 않는다.
어떻게 처리해야 할 지 한 시간은 고민한 것 같다...ㅎㅎ...
4. 최종 코드
def invert_dict(my_dict):
keys = my_dict.keys() # 새로 value가 될 애들
values = my_dict.values() # 새로 key가 될 애들
inverted_items = list(zip(values, keys)) # 자리 바꿔서 짝 지어주기
inverted_dict = {}
for value in values:
inverted_dict[value] = [] #새로운 key로 일단 dict 만들어주고
for i in range(len(inverted_items)):
inverted_dict[inverted_items[i][0]].append(inverted_items[i][1]) #새로운 쌍들 맞춰서 list에 추가해주기!
return inverted_dict
이전에 수업시간에 우리반의 다른 학생이 비슷한 함수를 구현한 적이 있는데
그 때, dict에서 key와 value가 들어올 공간을 미리 구현해 두셨던 것이 매우 인상 깊게 남아 있다.
그래서 그런 식으로 접근해 봤다.
zip함수를 통해 새로운 (key, value) 튜플들로 이루어진 리스트를 만들고
먼저 새로운 key값을 만들고 value엔 빈 리스트들을 만든 후에
해당하는 새로운 value들을 list의 append 메소드를 통해 구현한 것이다.
조건에 여타 다른 함수를 사용하지 말라고 적혀 있지는 않았기 때문에 zip함수를 사용하긴 했는데..
코테랑 알고리즘이랑 들어가면 이렇게 풀지 말라고 할 것 같기도 하다.
몰라~ 일단 나는 코딩이랑, 파이썬이랑 친해지는 중이기 때문에 내장함수 열심히 쓸 거다~~!!!
'Developing > Algorithm: Python' 카테고리의 다른 글
[python] 백준 boj14502 연구소 (0) | 2022.09.01 |
---|---|
[python] 백준 boj2109 순회강연 (아마도 그리디 풀이법) (0) | 2022.04.04 |
[python] 콜라츠 추측 파이썬으로 구현하기 (0) | 2022.01.29 |