Table of contents
1.
Introduction 
2.
Method 1: Accessing the key using the keys() method
2.1.
Python
3.
Method 2: Python access dictionary by key
3.1.
Python
3.2.
Python
4.
Method 3: Accessing key using keys() indexing
4.1.
Python
5.
Method 4: Python Dictionary update() function
5.1.
Python
5.2.
Python
6.
Frequently Asked Questions
6.1.
Can I use the in operator to check if a key exists in a dictionary?
6.2.
What happens if I try to access a key that doesn't exist in a dictionary?
6.3.
Can I modify the keys of a dictionary after it is created?
7.
Conclusion
Last Updated: Aug 10, 2024
Easy

Keys in Python

Author Gaurav Gandhi
0 upvote

Introduction 

In Python, a dictionary is a collection of key-value pairs. Each key in a dictionary is unique and is used to access its corresponding value. It’s very important to learn how to work with keys to effectively use dictionaries in your Python programs. 

Keys in Python

In this article, we will talk about different methods to access and manipulate keys in a Python dictionary.

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

The keys() method in Python returns a view object that contains all the keys in a dictionary. By using this method, you can easily access and iterate over the keys of a dictionary. 

For example:

  • Python

Python

my_dict = {'name': 'Rahul', 'age': 20, 'city': 'New York'}

keys = my_dict.keys()

print(keys) 
You can also try this code with Online Python Compiler
Run Code


Output

dict_keys(['name', 'age', 'city'])


In the above code, we define a dictionary called `my_dict` with three key-value pairs. We then use the `keys()` method to retrieve all the keys of the dictionary and store them in the `keys` variable. When we print `keys`, we get a view object that displays all the keys in the dictionary.

You can also iterate over the keys using a for loop:

for key in my_dict.keys():
    print(key)


This will output each key in the dictionary on a separate line:

name
age
city

Method 2: Python access dictionary by key

In Python, you can directly access the value of a dictionary by using its corresponding key. This is the most common and simple way to retrieve values from a dictionary. 

For example:

  • Python

Python

my_dict = {'name': 'Rinki', 'age': 21, 'city': 'London'}

name = my_dict['name']

age = my_dict['age']

print(name) 

print(age)
You can also try this code with Online Python Compiler
Run Code


Output

Rinki
21


In the above code, we have a dictionary `my_dict` with three key-value pairs. To access the value associated with a specific key, we use square brackets `[]` and provide the key inside them. For example, `my_dict['name']` retrieves the value associated with the key `'name'`, which is `'Rinki'`. Similarly, `my_dict['age']` retrieves the value associated with the key `'age'`, which is `21`.

It's important to note that if you try to access a key that doesn't exist in the dictionary, Python will raise a `KeyError`. To avoid this, you can use the `get()` method instead:

  • Python

Python

city = my_dict.get('city')

country = my_dict.get('country')

print(city)

print(country)
You can also try this code with Online Python Compiler
Run Code


Output

London
None


The `get()` method returns the value associated with the specified key if it exists in the dictionary. If the key doesn't exist, it returns `None` by default, instead of raising an error. You can also provide a default value as the second argument to `get()`, which will be returned if the key is not found:

country = my_dict.get('country', 'USA')
print(country)


Output

USA

Method 3: Accessing key using keys() indexing

In addition to using the `keys()` method to retrieve a view object of dictionary keys, you can also access individual keys by their index using the `keys()` method. This can be useful when you need to retrieve a specific key based on its position in the dictionary. 

For example:

  • Python

Python

my_dict = {'name': 'Harsh', 'age': 19, 'city': 'Mumbai'}

keys = list(my_dict.keys())

print(keys[0]) 

print(keys[1])

print(keys[2]) 
You can also try this code with Online Python Compiler
Run Code


Output

name
age
city


In the above code, we have a dictionary `my_dict` with three key-value pairs. We use the `keys()` method to retrieve a view object of the dictionary keys and then convert it to a list using the `list()` function. We store the list of keys in the `keys` variable.

Now, we can access individual keys by their index using square brackets `[]`. For example, `keys[0]` retrieves the first key in the dictionary, which is `'name'`. Similarly, `keys[1]` retrieves the second key, which is `'age'`, and `keys[2]` retrieves the third key, which is `'city'`.

It's important to note that the order of keys in a dictionary is not guaranteed to be the same as the order in which they were inserted. However, starting from Python 3.7, the order of keys is preserved according to the insertion order.

If you try to access an index that is out of range, Python will raise an `IndexError`. To avoid this, you can use the `len()` function to check the number of keys in the dictionary before accessing them by index:

num_keys = len(keys)
print(num_keys)


Output

3

Method 4: Python Dictionary update() function

The `update()` function in Python allows you to modify a dictionary by adding new key-value pairs or updating the values of existing keys. It provides a convenient way to merge the contents of one dictionary into another. 

For example:

  • Python

Python

my_dict = {'name': 'Sanjana', 'age': 22}

new_dict = {'city': 'Bangalore', 'country': 'India'}

my_dict.update(new_dict)

print(my_dict)
You can also try this code with Online Python Compiler
Run Code


Output

{'name': 'Sanjana', 'age': 22, 'city': 'Bangalore', 'country': 'India'}


In the above code, we have two dictionaries: `my_dict` and `new_dict`. We use the `update()` function to merge the key-value pairs from `new_dict` into `my_dict`. If a key from `new_dict` already exists in `my_dict`, its value will be updated with the value from `new_dict`. If a key from `new_dict` doesn't exist in `my_dict`, it will be added as a new key-value pair.

After calling `my_dict.update(new_dict)`, the contents of `new_dict` are merged into `my_dict`. The resulting `my_dict` will contain all the key-value pairs from both dictionaries.

You can also use the `update()` function to update a dictionary with key-value pairs directly, without the need for a separate dictionary:

  • Python

Python

my_dict = {'name': 'Ravi', 'age': 20}

my_dict.update(city='Pune', country='India')

print(my_dict)
You can also try this code with Online Python Compiler
Run Code


Output: 

{'name': 'Ravi', 'age': 20, 'city': 'Pune', 'country': 'India'}


In this case, we use keyword arguments in the `update()` function to directly specify the key-value pairs to be added or updated in `my_dict`.

Note: The `update()` function modifies the original dictionary in place and returns `None`. It provides a simple and efficient way to merge dictionaries or update key-value pairs in a dictionary.

Frequently Asked Questions

Can I use the in operator to check if a key exists in a dictionary?

Yes, you can use the in operator to check if a key exists in a dictionary. For example: if 'name' in my_dict:.

What happens if I try to access a key that doesn't exist in a dictionary?

If you try to access a key that doesn't exist in a dictionary using square brackets [], Python will raise a KeyError. To avoid this, you can use the get() method instead, which returns None or a default value if the key is not found.

Can I modify the keys of a dictionary after it is created?

No, dictionary keys are immutable in Python. Once a key is added to a dictionary, you cannot change its value. However, you can remove a key-value pair using the del keyword or the pop() method and then add a new key-value pair with the desired key.

Conclusion

In this article, we learned about different methods to access and manipulate keys in a Python dictionary. We explained the keys() method to retrieve a view object of dictionary keys, accessing values directly using keys, accessing keys by their index, and using the update() function to merge dictionaries or update key-value pairs.

You can also check out our other blogs on Code360

Live masterclass