개발/파이썬

딕셔너리에서 key 이름을 변경하는 방법

맨날치킨 2023. 1. 11. 16:05
반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Change the name of a key in dictionary

딕셔너리에서 key 이름을 변경하는 방법

 문제 내용 

How do I change the key of an entry in a Python dictionary?

Python 딕셔너리에서 항목의 key를 어떻게 변경할 수 있나요?

 

 

 

 높은 점수를 받은 Solution 

Easily done in 2 steps:

2단계로 쉽게 수행 가능합니다:
dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]

 

Or in 1 step:

또는 1단계로 수행할 수 있습니다:
dictionary[new_key] = dictionary.pop(old_key)

 

which will raise KeyError if dictionary[old_key] is undefined. Note that this will delete dictionary[old_key].

이렇게 하면 dictionary[old_key]가 정의되어 있지 않은 경우 KeyError가 발생합니다. dictionary[old_key]가 삭제됩니다.
>>> dictionary = { 1: 'one', 2:'two', 3:'three' }
>>> dictionary['ONE'] = dictionary.pop(1)
>>> dictionary
{2: 'two', 3: 'three', 'ONE': 'one'}
>>> dictionary['ONE'] = dictionary.pop(1)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 1

 

 

 가장 최근 달린 Solution 

You can use iff/else dictionary comprehension. This method allows you to replace an arbitrary number of keys in one line AND does not require you to change all of them.

딕셔너리 내포의 if/else문을 사용할 수도 있습니다. 이 방법은 한 줄에서 임의의 수의 키를 교체할 수 있으며, 모두 변경할 필요가 없습니다.
key_map_dict = {'a':'apple','c':'cat'}
d = {'a':1,'b':2,'c':3}
d = {(key_map_dict[k] if k in key_map_dict else k):v  for (k,v) in d.items() }

 

Returns {'apple':1,'b':2,'cat':3}

{'apple': 1, 'b': 2, 'cat': 3}를 반환합니다.

 

 

 

출처 : https://stackoverflow.com/questions/4406501/change-the-name-of-a-key-in-dictionary

반응형