그만큼 키() 방법 파이썬 사전 는 Python을 사용하여 삽입 순서대로 사전의 모든 키 목록을 표시하는 뷰 객체를 반환합니다.
통사론: dict.keys()
매개변수: 매개변수가 없습니다.
보고: 모든 키를 표시하는 뷰 객체가 반환됩니다. 이 뷰 객체는 사전의 변경 사항에 따라 변경됩니다.
방법 1: key() 메서드를 사용하여 키에 액세스
key() 함수가 사전에서 어떻게 작동하는지 보여주는 간단한 예입니다.
파이썬3
100만 몇 0
# Dictionary with three keys> Dictionary1>=> {>'A'>:>'Geeks'>,>'B'>:>'For'>,>'C'>:>'Geeks'>}> # Printing keys of dictionary> print>(Dictionary1.keys())> |
>
>
산출:
dict_keys(['A', 'B', 'C'])>
방법 2: 키별 Python 액세스 사전
다음을 사용하여 key()의 실제 적용을 시연합니다. 파이썬 루프 .
파이썬3
알파베타 가지치기
# initializing dictionary> test_dict>=> {>'geeks'>:>7>,>'for'>:>1>,>'geeks'>:>2>}> # accessing 2nd element using naive method> # using loop> j>=> 0> for> i>in> test_dict:> >if> (j>=>=> 1>):> >print>(>'2nd key using loop : '> +> i)> >j>=> j>+> 1> |
>
>
산출:
2nd key using loop : for TypeError: 'dict_keys' object does not support indexing>
시간 복잡도: O(n)
보조 공간: O(n)
메모: 두 번째 접근 방식은 작동하지 않습니다. dict_keys Python 3에서는 인덱싱을 지원하지 않습니다.
방법 3:keys() 인덱싱을 사용하여 키에 액세스
여기서는 먼저 모든 키를 추출한 다음 암시적으로 이를 Python 목록으로 변환하여 해당 요소에 액세스했습니다.
파이썬3
자바 int를 문자열로 변환
# initializing dictionary> test_dict>=> {>'geeks'>:>7>,>'for'>:>1>,>'geeks'>:>2>}> # accessing 2nd element using keys()> print>(>'2nd key using keys() : '>,>list>(test_dict.keys())[>1>])> |
>
>
산출:
2nd key using keys() : for>
방법 4: Python 사전 update() 함수
다음을 사용하여 사전 키를 업데이트하는 방법을 보여주기 위해 업데이트() 함수 . 여기서 사전이 업데이트되면 키도 자동으로 업데이트되어 변경 사항을 표시합니다.
파이썬3
자바 샘플 프로그램
# Dictionary with two keys> Dictionary1>=> {>'A'>:>'Geeks'>,>'B'>:>'For'>}> # Printing keys of dictionary> print>(>'Keys before Dictionary Updation:'>)> keys>=> Dictionary1.keys()> print>(keys)> # adding an element to the dictionary> Dictionary1.update({>'C'>:>'Geeks'>})> print>(>'
After dictionary is updated:'>)> print>(keys)> |
>
>
산출:
Keys before Dictionary Updation: dict_keys(['B', 'A']) After dictionary is updated: dict_keys(['B', 'A', 'C'])>