Python dictionary values() - How to get values of a dictionary

The values() returns values of a dictionary as a dict_values object.

d = {'book': 24, 'pen': '5'}

values = d.values()

print(values)  # dict_values([24, '5'])
print(type(values))  # <class 'dict_values'>

for v in values:
    print(v)

# 24
# 5

A Python dictionary has the values() method that returns its values that can be iterated. The next example shows how to get values as a list.

d = {'book': 24, 'pen': '5'}

values = d.values()
a = list(values)

print(values)  # dict_values([24, '5'])
print(a)  # [24, '5']

Example

d = {'x': 1, 'y': 3, 'z': 1}

values = d.values()

print(values)  # dict_values([1, 3, 1])

Even if some pairs have the same value, the values() returns all the values.

A trailing comma is ignored

d = {'x': 2, 'y': 3, }

values = d.values()

print(values)  # dict_values([2, 3])

items(), keys(), values()

d = {'x': 2, 'y': 3}

items = d.items()
keys = d.keys()
values = d.values()

print(items)  # dict_items([('x', 2), ('y', 3)])
print(keys)  # dict_keys(['x', 'y'])
print(values)  # dict_values([2, 3])

A Python dictionary has three important methods: items(), keys(), values().

The values are updated by updating the dictionary

d = {'x': 2, 'y': 3}

values = d.values()

d['z'] = 4

print(values)  # dict_values([2, 3, 4])

What the values() returns is updated by updating the original dictionary. Let's check the ids of the dictionary and values.

d = {'x': 2, 'y': 3}

values = d.values()

print(id(d))  # 4303240832
print(id(values))  # 4489176592

d['z'] = 4

print(id(d))  # 4303240832
print(id(values))  # 4489176592

Python Dictionary

Python Tutorial