Python dict_keys explained

Python dict_keys Explained

Python dict_keys Explained

In Python, dictionaries are a very common data type used to store key-value pairs. When we need to access all the keys in a dictionary, we can use the dict_keys type. This article will introduce the usage of dict_keys in detail and provide examples.

What is dict_keys

In Python, dict_keys is a view object of the dictionary’s keys. It stores the keys in the dictionary and maintains the order of the keys. dict_keys is a dynamic view object, meaning that when the dictionary changes, dict_keys is updated accordingly.

Characteristics of dict_keys

  1. dict_keys is a set-like object that supports operations such as intersection and union.
  2. dict_keys is dynamic and reflects changes to dictionary keys in real time.
  3. dict_keys is iterable and can be used in loops.

How to Get dict_keys

You can use the dict.keys() method to get a dictionary’s dict_keys view object. Let’s look at an example:

# Create a dictionary
my_dict = {‘name’: ‘Geek-docs’, ‘website’: ‘geek-docs.com’, ‘github’: ‘github.com/geek-docs’}

# Get the dictionary’s dict_keys object
keys = my_dict.keys()

print(keys)

Running result:

dict_keys(['name', 'website', 'github'])

In the above example, we use the my_dict.keys() method to get the dict_keys object of the dictionary my_dict and print the keys.

Operating with dict_keys

dict_keys objects support some set operations, such as intersection and union. Let’s look at an example:

dict1 = {‘a’: 1, ‘b’: 2, ‘c’: 3}
dict2 = {‘b’: 2, ‘c’: 3, ‘d’: 4}

keys1 = dict1.keys()
keys2 = dict2.keys()

# Find the intersection of the keys of two dictionaries
intersection_keys = keys1 & keys2
print(intersection_keys)

# Find the union of the keys of two dictionaries
union_keys = keys1 | keys2
print(union_keys)

Running result:

{'b', 'c'}
{'a', 'b', 'c', 'd'}

In the above example, we intersect and union the keys of two dictionaries and obtain the result.

Iterating over dict_keys

Since dict_keys is an iterable object, we can iterate over it in a for loop. Here’s an example:

my_dict = {'name': 'Geek-docs', 'website': 'geek-docs.com', 'github': 'github.com/geek-docs'}

keys = my_dict.keys()

for key in keys:
print(key)

Result:

name
website
github

In the example above, we iterate over the dict_keys object in the dictionary my_dict using a for loop and print the value of each key.

Using the in Keyword to Check if a Key Exists

We can use the in keyword to check whether a key exists in dict_keys. Let’s look at an example:

my_dict = {'name': 'Geek-docs', 'website': 'geek-docs.com', 'github': 'github.com/geek-docs'}

keys = my_dict.keys()

if 'name' in keys:
print('The name key exists')
else:
print('The name key does not exist')

if 'email' in keys:
print('The email key exists')
else:
print('The email key does not exist')

Running result: