티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Rename a dictionary key
딕셔너리 키 이름 바꾸기
문제 내용
Is there a way to rename a dictionary key, without reassigning its value to a new name and removing the old name key; and without iterating through dict key/value?
값을 새 이름으로 다시 할당하고 이전 이름 키를 제거하지 않고 dict 키/값을 반복하지 않으면서 사전 키의 이름을 바꾸는 방법이 있습니까?
In case of OrderedDict
do the same, while keeping that key's position.
OrderedDict의 경우 키의 위치를 유지하면서 동일하게 수행합니다.
높은 점수를 받은 Solution
For a regular dict, you can use:
일반 딕셔너리의 경우 다음을 사용할 수 있습니다.
mydict[k_new] = mydict.pop(k_old)
This will move the item to the end of the dict, unless k_new
was already existing in which case it will overwrite the value in-place.
k_new가 이미 존재하지 않는 한 항목이 딕셔너리의 끝으로 이동합니다. 이 경우 항목은 in-place 값을 덮어씁니다.
For a Python 3.7+ dict where you additionally want to preserve the ordering, the simplest is to rebuild an entirely new instance. For example, renaming key 2
to 'two'
:
추가적으로 순서를 보존하고자 하는 Python 3.7+ 딕셔너리의 경우, 가장 간단한 것은 완전히 새로운 인스턴스를 재구축하는 것이다. 예를 들어 키 2의 이름을 'two'로 변경합니다.
>>> d = {0:0, 1:1, 2:2, 3:3}
>>> {"two" if k == 2 else k:v for k,v in d.items()}
{0: 0, 1: 1, 'two': 2, 3: 3}
The same is true for an OrderedDict
, where you can't use dict comprehension syntax, but you can use a generator expression:
OrderedDict의 경우에도 마찬가지로 dict 이해 구문을 사용할 수 없지만 생성자 식을 사용할 수 있습니다.
OrderedDict((k_new if k == k_old else k, v) for k, v in od.items())
Modifying the key itself, as the question asks for, is impractical because keys are hashable which usually implies they're immutable and can't be modified.
질문에서 요구하는 것처럼 키 자체를 수정하는 것은 비실용적입니다. 키는 일반적으로 변경할 수 없고 수정할 수 없음을 의미하는 해시 가능이기 때문입니다.
가장 최근 달린 Solution
In case of renaming all dictionary keys:
모든 딕셔너리 키의 이름을 변경하는 경우:
target_dict = {'k1':'v1', 'k2':'v2', 'k3':'v3'}
new_keys = ['k4','k5','k6']
for key,n_key in zip(target_dict.keys(), new_keys):
target_dict[n_key] = target_dict.pop(key)
출처 : https://stackoverflow.com/questions/16475384/rename-a-dictionary-key
'개발 > 파이썬' 카테고리의 다른 글
다른 파일에서 변수 가져오기 (0) | 2022.12.24 |
---|---|
중첩된 Python dict를 객체로 변환하기 (0) | 2022.12.24 |
Cython: "fatal error: numpy/arrayobject.h: No such file or directory" 오류 수정하기 (0) | 2022.12.23 |
여러 CSV 파일을 판다스로 가져와 하나의 데이터프레임으로 만들기 (0) | 2022.12.23 |
리스트를 문자열로 변환하기 (0) | 2022.12.23 |