Python get keys from dict:
The keys() method returns a new view of the dictionary keys as a list referred as “dict_keys”.
Method signature
The signature for the keys() method is as shown below. Here, d refers to the dictionary and v is a view over the dictionary.
v=d.keys()
Method parameters and return type
- The keys() method takes no parameters.
- However, it returns a view object that displays keys as a list.
Python Dictionary keys Examples:
Example 1:
In this case, let us take a dictionary with numbers assigned to colour names. Here, we will extract all the keys as a list. Moreover, we can see list is named as dict_keys.
#Initializing
color={1:"Red",2:"Blue",3:"Green"}
# Using keys method
v1=color.keys()
#Printing
print("View has ",v1)
Output
View has dict_keys([1, 2, 3])
Example 2:
Let us take a dictionary with numbers assigned to a list containing names in this example. Firstly, let us add the new key-value pair to the dictionary. As we can see, it automatically updates the view.
#Initializing
n={1:["Jim","Kim"],2:["John","Tom"],3:["Riya","Siya"]}
v1=n.keys()
#Printing
print("Before update view has ",v1)
#Adding new key value pair
n.update({4:["X","Y"]})
#Printing
print("After update view has ",v1)
Output
Before update view has dict_keys([1, 2, 3])
After update view has dict_keys([1, 2, 3, 4])
Example 3:
We will take a dictionary with the department name and student name in this case. Here, we will delete the key “Comp”. As a result, changes are reflected in the view also.
#Initializing
n={"Comp":"Jim","IT":"Tom","EXTC":"Siya"}
# Using keys method
v1=n.keys()
#Printing
print("Before Delete view has ",v1)
del(n["Comp"])
#Printing
print("After Delete view has ",v1)
Output
Before Delete view has dict_keys(['Comp', 'IT', 'EXTC'])
After Delete view has dict_keys(['IT', 'EXTC'])
Conclusion
The keys() method extracts keys from the dictionary as a list. Just because this is a view over the dictionary. So, all the updates made to the dictionary are also reflected in the view.
References
Happy Learning 🙂