Python Dictionary keys() method

您所在的位置:网站首页 items。 Python Dictionary keys() method

Python Dictionary keys() method

2023-09-25 12:14| 来源: 网络整理| 查看: 265

The keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion using Python.

Syntax: dict.keys()

Parameters: There are no parameters.

Returns: A view object is returned that displays all the keys. This view object changes according to the changes in the dictionary.

Method 1: Accessing the key using the keys() method

A simple example to show how the keys() function works in the dictionary.

Python3

# Dictionary with three keysDictionary1 = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'} # Printing keys of dictionaryprint(Dictionary1.keys())

Output: 

dict_keys(['A', 'B', 'C'])Method 2: Python access dictionary by key

Demonstrating the practical application of keys() using the Python loop.

Python3

# initializing dictionarytest_dict = {"geeks": 7, "for": 1, "geeks": 2} # accessing 2nd element using naive method# using loopj = 0for i in test_dict:    if (j == 1):        print('2nd key using loop : ' + i)    j = j + 1

Output: 

2nd key using loop : for TypeError: 'dict_keys' object does not support indexing

Time Complexity: O(n)Auxiliary Space: O(n)

Note: The second approach would not work because dict_keys in Python 3 do not support indexing. 

Method 3: Accessing key using keys() indexing

Here, we first extracted all the keys and then we implicitly converted them into the Python list to access the element from it.

Python3

# initializing dictionarytest_dict = {"geeks": 7, "for": 1, "geeks": 2} # accessing 2nd element using keys()print('2nd key using keys() : ', list(test_dict.keys())[1])

Output: 

2nd key using keys() : forMethod 4: Python Dictionary update() function

To show how to update the dictionary keys using the update() function. Here, when the dictionary is updated, keys are also automatically updated to show the changes.

Python3

# Dictionary with two keysDictionary1 = {'A': 'Geeks', 'B': 'For'} # Printing keys of dictionaryprint("Keys before Dictionary Updation:")keys = Dictionary1.keys()print(keys) # adding an element to the dictionaryDictionary1.update({'C': 'Geeks'}) print('\nAfter dictionary is updated:')print(keys)

Output: 

Keys before Dictionary Updation: dict_keys(['B', 'A']) After dictionary is updated: dict_keys(['B', 'A', 'C'])


【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3