Imagine a situation where a dictionary is created in Python that is used to store various attributes (keys) of a Book such as Title, Author, Pages, Edition, Publication, Year, etc. A user might want to fetch these keys to check how many parameters exist. That’s where the Python dictionary keys() function comes in handy. This Python dictionary keys() method is used to retrieve all the keys so we know what kind of information is stored.
Definition
- Python dictionary keys() function is used to return a new view object that contains a list of all the keys in the dictionary.
- The Python dictionary keys() method returns an object that contains all the keys in a dictionary.
keys() Syntax
To use the Python dictionary keys() function, we must follow the below syntax:
dict_name.keys()
keys() Parameters
The dictionary keys() function does not accept any arguments or parameters.
Return value from keys()
A view object is returned by the function which consists of a list of all the keys in the dictionary. It is of type dict_keys(). If the dictionary is changed, the view object will also reflect these changes and display the output accordingly.
Example 1: How keys() work?
Let us look at few examples to understand how the Python dictionary keys() function works.
Note – The order in which the keys are displayed in the list might not always be the same.
Example
# Python program to illustrate keys()
# creating a dictionary
stud = {'Name': 'Emily', 'Age': 28, 'Salary': 68000, 'City': 'Boston', 'Education': 'PG'}
keys = stud.keys()
print(keys)
# another dictionary example
items = {'Fruit': 'Apple', 'Flower': 'Rose', 'Vegetable': 'Cabbage'}
print(items.keys())
# empty dictionary
my_dict = {}
print(my_dict.keys())
Output
dict_keys(['Name', 'Age', 'Salary', 'City', 'Education'])
dict_keys(['Fruit', 'Flower', 'Vegetable'])
dict_keys([])
First, we created a Python dictionary named stud that contains the Students data. Then, using stud.keys(), we get a list of all the keys in the dictionary. This list is then assigned to the Python variable keys. The value of the keys variable is then printed to the console.
Example 2: How keys() work when the dictionary is updated?
As we add new keys to our dictionary, the keys() method keeps track of them. In the below example, when the dictionary is updated, keys are also updated to reflect the changes.
Example
# Python program to illustrate keys()
data = {'Name': 'David', 'Age': 49}
print('Keys Before updation:', data.keys())
# adding new key-value pair to the dictionary
data.update({'Salary': 50000, 'Profession': 'Marketing Head'})
print('Keys After updation:', data.keys())
Output
Keys Before updation: dict_keys(['Name', 'Age'])
Keys After updation: dict_keys(['Name', 'Age', 'Salary', 'Profession'])
Example 3: Practical Applications of keys()
The Python dictionary keys() function can be used to access dictionary elements in the same way that we can access list elements; however, without the usage of keys(), no other mechanism provides a way to access dictionary keys as a list by index. This is illustrated in the following example.
Example
inventory = {'Pencils': 90, 'Pens': 170, 'Papers': 300, 'Books': 420}Â
# Calling methodÂ
for i in inventory.keys():Â
   if inventory[i] > 100:Â
       print('We have sufficient inventory of:', i)
Output
We have sufficient inventory of: Pens
We have sufficient inventory of: Papers
We have sufficient inventory of: Books
Frequently Asked Questions
Q1. What are keys() in the Python dictionary?
Keys are data objects that can be assigned specific values in the dictionary. A colon (:) separates each key from its value, commas divide the elements, and curly braces surround the entire thing. To fetch these keys from the dictionary, we use the Python dictionary keys() function.
Python dictionary keys() function is used to return a view object that contains a list of all the keys in the dictionary. This Python dictionary keys() method is used to retrieve all the keys so we know what kind of information is stored.
Q2. How do you use dictionary keys() in Python?
To use the Python dictionary keys() function, we must follow the below syntax:
dict_name.keys()
The dictionary keys() function does not accept any arguments or parameter.
Example
num = {'I': 'One', 'II': 'Two', 'III': 'Three'}
keys = num.keys()
print('Keys in Dictionary:', keys)
num.update({'IV': 'Four', 'V': 'Five'})
print('Updated keys:', keys)
Output
Keys in Dictionary: dict_keys(['I', 'II', 'III'])
Updated keys: dict_keys(['I', 'II', 'III', 'IV', 'V'])
Q3. How do I get the dictionary keys in a list?
When we use the Python keys() function a view object is returned by the function which consists of all the keys in the dictionary. To convert this output into a list we can use multiple methods. The most common and easy ones being:
- Typecasting to list
Example
num = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four'}
keys = num.keys()
print('Keys in Dictionary:', keys)
# prints only the list
print('List of Keys in Dictionary:', list(keys))
Output
Keys in Dictionary: dict_keys([1, 2, 3, 4])
List of Keys in Dictionary: [1, 2, 3, 4]
- Unpacking with *
Example
num = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four'}
keys = num.keys()
print('Keys in Dictionary:', [*keys])
Output
Keys in Dictionary: [1, 2, 3, 4]
- Most basic approach
Example
def getList(num):
   list = []
   for i in num.keys():
       list.append(i)
   return list
num = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four'}
print('List of Keys in Dictionary:', getList(num))
Output
List of Keys in Dictionary: [1, 2, 3, 4]
Q4. What are few restrictions to keys in Python?
There are a few constraints that dictionary keys must follow:
- For starters, a given key can only occur once in a dictionary. Duplicate keys are not permitted. It will just replace the value if it is used more than once.
- Second, a dictionary key must be of an immutable type. Several of the immutable types you’re familiar with—integer, float, text, tuple, and Boolean—have already been used as dictionary keys. However, because lists and dictionaries are mutable, neither can they be used as dictionary keys.
Leave a Reply