No.037 [Pythhon] 회의 키 이름 바꾸기

4540 단어 Pythonprogramming

이번에는 Diquenery 열쇠의 이름을 어떻게 바꾸는지 적어 봅시다.


I'll write about "key-name change of a dictionary ", in python"on this page.

■ 기존 요소 삭제, 새로운 요소 추가


 Delete old factors and add new factors
>>> # delの使用
>>> 
>>> d = {"key1":1, "key2":2, "key3":3}
>>> 
>>> d["key10"] = d["key1"]
>>> 
>>> del d["key1"]
>>> 
>>> print(d)
{'key2': 2, 'key3': 3, 'key10': 1}
>>> # pop()の使用
>>> # pop():要素を削除+そのキーの値取得が可能
>>> 
>>> d = {"key1":1, "key2":2, "key3":3}
>>> 
>>> print(d.pop("key1"))
1
>>> 
>>> print(d)
{'key2': 2, 'key3': 3}
>>> # del文よりもシンプルに記載が可能
>>> 
>>> d = {"key1":1, "key2":2, "key3":3}
>>> 
>>> d ["key10"] = d.pop("key1")
>>> 
>>> print(d)
{'key2': 2, 'key3': 3, 'key10': 1}
>>> # 注意:デフォルトの状態では、第一引数に存在しないキーを指定するとエラーになる
>>> 
>>> d = {"key1":1, "key2":2, "key3":3}
>>> 
>>> print(d.pop("key10"))
Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    print(d.pop("key10"))
KeyError: 'key10'
>>> # 第二引数の値を指定の場合、エラーにならない
>>> 
>>> print(d.pop('key10', None))
None
>>> 
>>> print(d)
{'key1': 1, 'key2': 2, 'key3': 3}

■ 키 이름 바꾸기 함수 정의


 Define a function when a key-name is changed
>>> # pop()により、以下の関数定義ができる
>>> 
>>> def change_dict _key(d, old_key, new_key, default_value=None):

SyntaxError: invalid syntax
>>> def change_dict_key(d, old_key, new_key, default_value=None):
     d[new_key] = d.pop(old_key, default_value)


>>> d = {"key1":1, "key2":2, "key3":3}
>>> change_dict_key(d, "key1", "key10")
>>> 
>>> print(d)
{'key2': 2, 'key3': 3, 'key10': 1}
>>> # 存在しないキーを指定すると、第三引数に指定の値が追加される
>>> 
>>> d = {"key1":1, "key2":2, "key3":3}
>>> change_dict_key(d, "key10", "key100")
>>> 
>>> print(d)
{'key1': 1, 'key2': 2, 'key3': 3, 'key100': None}
>>> 
>>> 
>>> d = {"key1":1, "key2":2, "key3":3}
>>> change_dict_key(d, "key10", "key100", 100)
>>> 
>>> print(d)
{'key1': 1, 'key2': 2, 'key3': 3, 'key100': 100}
>>> # 補足:既存のキーの値を残す場合、setdefault()を使う
>>> 
>>> def change_dict_key_setdefault(d, old_key, new_key, default_value=None):
    d.setdefault(new_key, d.pop(old_key, default_value))


>>> d = {"key1":1, "key2":2, "key3":3}
>>> change_dict_key_setdefault(d, "key1", "key2")
>>> 
>>> print(d)
{'key2': 2, 'key3': 3}
>>> # 新規のキーが既存のキーでない場合
>>> 
>>> d = {"key1":1, "key2":2, "key3":3}
>>> change_dict_key_setdefault(d, 'key1', 'key10')
>>> 
>>> print(d)
{'key2': 2, 'key3': 3, 'key10': 1}
>>> 
>>> d = {"key1":1, "key2":2, "key3":3}
>>> change_dict_key_setdefault(d, "key10", "key100")
>>> 
>>> print(d)
{'key1': 1, 'key2': 2, 'key3': 3, 'key100': None}
수시로 업데이트되므로 정기적으로 구독해주세요.
I'll update my article at all times.
So, please subscribe my articles from now on.
본 보도에 관하여 만약 무슨 요구가 있으면 마음대로 메시지를 남겨 주십시오!
If you have some requests, please leave some messages! by You-Tarin
또한 Qita에 투고한 내용은 언제든지 블로그에 가고 싶으니 잘 부탁드립니다.

좋은 웹페이지 즐겨찾기