개발/Python

[파이썬] dictionary에서 key 이름 변경

MinorMan 2021. 1. 9. 19:00
반응형

<질문>

Python 사전에서 항목의 키를 변경하고 싶습니다.

이 작업을 수행하는 간단한 방법이 있습니까?


<답변1>

2 단계로 쉽게 완료 :

dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]

또는 1 단계 :

dictionary[new_key] = dictionary.pop(old_key)

올릴 것이다KeyError만약dictionary[old_key]정의되지 않았습니다. 이의지지우다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

<답변2>

모든 키를 변경하려면 :

d = {'x':1, 'y':2, 'z':3}
d1 = {'x':'a', 'y':'b', 'z':'c'}

In [10]: dict((d1[key], value) for (key, value) in d.items())
Out[10]: {'a': 1, 'b': 2, 'c': 3}

단일 키를 변경하려는 경우 : 위의 제안 중 하나를 사용할 수 있습니다.


<답변3>

팝앤 프레쉬

>>>a = {1:2, 3:4}
>>>a[5] = a.pop(1)
>>>a
{3: 4, 5: 2}
>>> 

<답변4>

파이썬 2.7 이상에서는 사전 이해력을 사용할 수 있습니다. 이것은 DictReader를 사용하여 CSV를 읽는 동안 만난 예입니다. 사용자는 모든 열 이름에 ':'접미사를 붙였습니다.

ori_dict = {'key1:' : 1, 'key2:' : 2, 'key3:' : 3}

키에서 후행 ':'을 제거하려면 :

corrected_dict = { k.replace(':', ''): v for k, v in ori_dict.items() }


<답변5>

키는 사전이 값을 조회하는 데 사용하는 것이므로 실제로 변경할 수 없습니다. 가장 가까운 방법은 이전 키와 관련된 값을 저장하고 삭제 한 다음 대체 키와 저장된 값으로 새 항목을 추가하는 것입니다. 다른 답변 중 일부는이를 수행 할 수있는 다양한 방법을 보여줍니다.


<답변6>

복잡한 dict가있는 경우 dict 내에 dict 또는 목록이 있음을 의미합니다.

myDict = {1:"one",2:{3:"three",4:"four"}}
myDict[2][5] = myDict[2].pop(4)
print myDict

Output
{1: 'one', 2: {3: 'three', 5: 'four'}}

<답변7>

이를 수행하는 직접적인 방법은 없지만 삭제 후 할당 할 수 있습니다.

d = {1:2,3:4}

d[newKey] = d[1]
del d[1]

또는 대량 키 변경 수행 :

d = dict((changeKey(k), v) for k, v in d.items())

<답변8>

d = {1:2,3:4}

목록 요소 p = [ 'a', 'b']의 키를 변경한다고 가정합니다. 다음 코드가 수행합니다.

d=dict(zip(p,list(d.values()))) 

그리고 우리는

{'a': 2, 'b': 4}

<답변9>

사전의 모든 키를 변환하려면

이것이 귀하의 사전이라고 가정하십시오.

>>> sample = {'person-id': '3', 'person-name': 'Bob'}

샘플 사전 키에서 모든 대시를 밑줄로 변환하려면 :

>>> sample = {key.replace('-', '_'): sample.pop(key) for key in sample.keys()}
>>> sample
>>> {'person_id': '3', 'person_name': 'Bob'}

<답변10>

이 함수는 dict와 키 이름을 바꾸는 방법을 지정하는 또 다른 dict를 가져옵니다. 이름이 변경된 키와 함께 새 사전을 반환합니다.

def rekey(inp_dict, keys_replace):
    return {keys_replace.get(k, k): v for k, v in inp_dict.items()}

테스트:

def test_rekey():
    assert rekey({'a': 1, "b": 2, "c": 3}, {"b": "beta"}) == {'a': 1, "beta": 2, "c": 3}

<답변11>

한 번에 모든 키를 변경하는 경우. 여기서 나는 열쇠를 형태소입니다.

a = {'making' : 1, 'jumping' : 2, 'climbing' : 1, 'running' : 2}
b = {ps.stem(w) : a[w] for w in a.keys()}
print(b)
>>> {'climb': 1, 'jump': 2, 'make': 1, 'run': 2} #output

<답변12>

이렇게하면 모든 사전 키가 소문자로 표시됩니다. 중첩 된 사전 또는 목록이 있더라도. 유사한 작업을 수행하여 다른 변환을 적용 할 수 있습니다.

def lowercase_keys(obj):
  if isinstance(obj, dict):
    obj = {key.lower(): value for key, value in obj.items()}
    for key, value in obj.items():         
      if isinstance(value, list):
        for idx, item in enumerate(value):
          value[idx] = lowercase_keys(item)
      obj[key] = lowercase_keys(value)
  return obj 
json_str = {"FOO": "BAR", "BAR": 123, "EMB_LIST": [{"FOO": "bar", "Bar": 123}, {"FOO": "bar", "Bar": 123}], "EMB_DICT": {"FOO": "BAR", "BAR": 123, "EMB_LIST": [{"FOO": "bar", "Bar": 123}, {"FOO": "bar", "Bar": 123}]}}

lowercase_keys(json_str)


Out[0]: {'foo': 'BAR',
 'bar': 123,
 'emb_list': [{'foo': 'bar', 'bar': 123}, {'foo': 'bar', 'bar': 123}],
 'emb_dict': {'foo': 'BAR',
  'bar': 123,
  'emb_list': [{'foo': 'bar', 'bar': 123}, {'foo': 'bar', 'bar': 123}]}}

<답변13>

동일한 값을 여러 키와 연결하거나 키를 제거하고 동일한 값을 가진 새 키를 다시 추가 할 수 있습니다.

예를 들어 키-> 값이있는 경우 :

red->1
blue->2
green->4

추가 할 수없는 이유가 없습니다.purple->2또는 제거red->1그리고 추가orange->1


<답변14>

다단계 사전에서 모든 키 발생을 바꾸려는 경우 메서드입니다.

함수는 사전에 특정 키가 있는지 확인한 다음 하위 사전을 반복하고 함수를 재귀 적으로 호출합니다.

def update_keys(old_key,new_key,d):
    if isinstance(d,dict):
        if old_key in d:
            d[new_key] = d[old_key]
            del d[old_key]
        for key in d:
            updateKey(old_key,new_key,d[key])

update_keys('old','new',dictionary)

<답변15>

완전한 솔루션의 예

원하는 매핑을 포함하는 json 파일을 선언하십시오.

{
  "old_key_name": "new_key_name",
  "old_key_name_2": "new_key_name_2",
}

로드

with open("") as json_file:
    format_dict = json.load(json_file)

이 함수를 만들어 매핑으로 딕셔너리를 형식화하십시오.

def format_output(dict_to_format,format_dict):
  for row in dict_to_format:
    if row in format_dict.keys() and row != format_dict[row]:
      dict_to_format[format_dict[row]] = dict_to_format.pop(row)
  return dict_to_format

<답변16>

팝의 위치에 유의하십시오.
pop () 뒤에 삭제할 키를 입력하십시오.
orig_dict [ 'AAAAA'] = orig_dict.pop ( 'A')

orig_dict = {'A': 1, 'B' : 5,  'C' : 10, 'D' : 15}   
# printing initial 
print ("original: ", orig_dict) 

# changing keys of dictionary 
orig_dict['AAAAA'] = orig_dict.pop('A')
  
# printing final result 
print ("Changed: ", str(orig_dict)) 


<답변17>

현재 키 이름을 새 이름으로 변경할 수있는 아래에이 함수를 작성했습니다.

def change_dictionary_key_name(dict_object, old_name, new_name):
    '''
    [PARAMETERS]: 
        dict_object (dict): The object of the dictionary to perform the change
        old_name (string): The original name of the key to be changed
        new_name (string): The new name of the key
    [RETURNS]:
        final_obj: The dictionary with the updated key names
    Take the dictionary and convert its keys to a list.
    Update the list with the new value and then convert the list of the new keys to 
    a new dictionary
    '''
    keys_list = list(dict_object.keys())
    for i in range(len(keys_list)):
        if (keys_list[i] == old_name):
            keys_list[i] = new_name

    final_obj = dict(zip(keys_list, list(dict_object.values()))) 
    return final_obj

JSON을 호출하고 다음 줄로 이름을 바꿀 수 있다고 가정합니다.

data = json.load(json_file)
for item in data:
    item = change_dictionary_key_name(item, old_key_name, new_key_name)

목록에서 사전 키로의 변환은 여기에서 찾을 수 있습니다.
https://www.geeksforgeeks.org/python-ways-to-change-keys-in-dictionary/


<답변18>

이 정확한 답을 보지 못했습니다.

dict['key'] = value

객체 속성에 대해서도이 작업을 수행 할 수 있습니다. 다음을 수행하여 사전으로 만드십시오.

dict = vars(obj)

그런 다음 사전처럼 객체 속성을 조작 할 수 있습니다.

dict['attribute'] = value
반응형