keys() method in Python Dictionary

A Python dictionary mainly consists of items, which is basically a key:value pair. In previous article, we covered items() method to return a list of items in a dictionary. Here, through keys() method – we would have a view object which would contain a list of all the keys in a Python dictionary.

So, a keys() method would return a view object. It reflects the changes made to the dictionary, we cover more about in next section.

Following is the syntax for keys() method

dictionary_name.keys()

We next discuss it with relevant examples next.

keys() method in Python Dictionary

Let’s say we have dictionary, x –

x = {"name":"abc", "age":24, "address":"xyz, qwerty"}

Example I. To view dictionary keys, use the following code –

y = x.keys()

Thereafter, use print() method –

print(y)

It would return with –

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

As expected, it provides us a list of keys which we there in variable y.

Example II. As already discussed, view objects reflect changes made to the Python dictionary. So, adding an item to the Python dictionary would update the view object as well. Let’s see how things work with view object through an example.

Continuing with the dictionary, x – which we declared initially. First, we go with usual code –

y = x.keys()
print("Without any changes: ", y)

Now, we add an item to the dictionary and won’t use the y = x.keys() code again to confirm that any changes made to the dictionary modifies the view object as well.

x ['test'] = "test_outcome"
print("With changes: ", y)

This would return with –

Without any changes: dict_keys(['name', 'age', 'address'])
With changes: dict_keys(['name', 'age', 'address', 'test'])

Clearly, the view object shows us the update when we make changes to the dictionary. We have added a key – test and value – test_outcome. Through keys() method we can only view a list of keys. Therefore, the value of the item isn’t shown.

In conclusion, we have discussed keys() method in Python dictionary.