Python Dictionary keys() method
Last Updated :
21 Aug, 2024
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 keys
Dictionary1 = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
# Printing keys of dictionary
print(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 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
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.
Python
# 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])
Output:
2nd key using keys() : for
Method 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 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('\nAfter dictionary is updated:')
print(keys)
Output:
Keys before Dictionary Updation:
dict_keys(['B', 'A'])
After dictionary is updated:
dict_keys(['B', 'A', 'C'])
Python Dictionary keys() method – FAQs
What Does the keys() Method Do in Python?
The keys() method in Python is used with dictionaries to return a view of all the keys in the dictionary. This view object reflects the changes made to the dictionary, meaning if the dictionary is updated, the view shows the new keys.
Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = my_dict.keys()
print(keys) # Output: dict_keys(['a', 'b', 'c'])
How to Reference Keys in Dictionary in Python?
Keys in a dictionary can be referenced using the square bracket notation similar to indexing arrays but using the key name instead of numerical indexes.
Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict['a'] # Access the value associated with the key 'a'
print(value) # Output: 1
What Does object.keys() Do?
In the context of Python, object.keys() might seem misleading as Python objects do not have a direct keys() method. However, in JavaScript, Object.keys() is a method used to return an array of a given object’s own enumerable property names, iterated in the same order that a normal loop would. If you’re dealing with Python, ensure you’re using this method with dictionaries only.
Can a Dictionary Have Duplicate Keys?
No, a dictionary in Python cannot have duplicate keys. Each key must be unique within a dictionary. If you attempt to assign a value to an already existing key, the previous value associated with that key will be overwritten with the new value.
Example:
my_dict = {'a': 1, 'b': 2}
my_dict['a'] = 3 # This will overwrite the value of key 'a' from 1 to 3
print(my_dict) # Output: {'a': 3, 'b': 2}
Which Key is Used to Define Methods in Python?
The term “key” isn’t typically used to describe defining methods in Python. Instead, methods are defined using the def keyword followed by the method name and parameters.
Example:
class MyClass:
def my_method(self):
print("Hello, World!")
# Creating an instance of MyClass
obj = MyClass()
obj.my_method() # Output: Hello, World!
The def keyword is crucial for defining both standalone functions and methods within classes in Python. There is no specific “key” used in this context