values() method in Python Dictionary

This is in continuation to our previous articles – items() method in Python Dictionary & keys() method in Python Dictionary. Here, we discuss about values in an item of a dictionary. A dictionary contains items which are in the form of key:value pairs. With the help of values() method, we can have a view object which would contain a list of all values in a Python dictionary.

Following is the syntax for values() method –


As it returns with a view object, therefore view object would reflect any changes made to the dictionary. We cover more about it through relevant examples next.

values() method in Python Dictionary

Let’s say we have dictionary, x –

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

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

y = x.values()

Thereafter, use print() method –


It would return with –

dict_values(['abc', 24, 'xyz, qwerty'])

As expected, it provides us a list of values – stored in variable y.

Example II. As already discussed, view objects reflect changes made to the Python dictionary. So, removing an item from the Python dictionary would update the view object as well. Here, we will see it functioning with the help of following example.

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

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

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

print("With changes: ", y)

This would return with –

Without any changes: dict_values(['abc', 24, 'xyz, qwerty'])
With changes: dict_values([24, 'xyz, qwerty'])

Clearly, the view object shows us the update when we make changes to the dictionary. We have removed an item with key – “name”. Through values() method we can only view a list of values. Therefore, the key of the item isn’t shown.

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

Similar Posts