Python3 Dictionary values() Method
Description
The Python dictionary's values() The method retrieves all values in a dictionary and returns a dict_values view object.
The view object is not a list but a dynamic view associated with the original dictionary. When values change or key/value pairs are added or removed, the view reflects those changes.
For example:
dict_values(['Runoob', 7])
values() The returned view has the following characteristics:
- **Supports iteration:** you can use a
forloop to access all values in the dictionary. - **Dynamic updates:** when the original dictionary changes, the view reflects the latest contents.
- **Duplicates allowed:** different keys may have the same value.
- **No indexing:** you cannot directly use
dict.values()[0]to get the first value. - **Order preserved:** Python 3.7 and above iterates values in the insertion order of the dictionary's keys.
The difference between dict.keys() and dict.items() In the same way,values() It returns a dictionary view object.
To convert the view to a list, you can use list() function in Vue 3.
Syntax
values() method syntax:
dict.values()
Parameters
none.
Return Value
Returns a dict_values A view object containing all values in the dictionary.
This method does not modify the original dictionary, nor does it directly create a separate copy of the value list.
Example
The following example shows values() Basic usage of the method.
Example
#!/usr/bin/python3
tinydict
=
{
'Name'
:
'Runoob'
,
'Age'
:
7
}
values
=
tinydict.
values
(
)
(
values
)
(
type
(
values
)
)
Execution result:
dict_values(['Runoob', 7])
As you can see,values() returns a dict_values object, not an ordinary list.
Example 2: iterating over the dictionary's values
can be used via for Loop traversal values() the returned view.
Example
dishes
=
{
'eggs'
:
2
,
'sausage'
:
1
,
'bacon'
:
1
,
'spam'
:
500
}
for
value
in
dishes.
values
(
)
:
(
value
)
Execution result:
2
1
1
500
Because Python 3.7 and above guarantees dictionaries preserve insertion order, the iterated values correspond to the insertion order of the keys.
Example 3: summing all values in a dictionary
If all values in the dictionary are numbers, you can use the sum() function to compute the total.
Example
dishes
=
{
'eggs'
:
2
,
'sausage'
:
1
,
'bacon'
:
1
,
'spam'
:
500
}
total
=
sum
(
dishes.
values
(
)
)
(
"Total:"
,
total
)
Execution result:
总数: 504
Use sum(dishes.values()) You can sum the numeric values in a dictionary directly without writing a loop manually.
**Note:** if the dictionary contains values of types that do not support addition, such as strings, using sum() directly may raise TypeError。
Example 4: converting values() to a list
Because dict_values The object does not support indexing, so its elements cannot be accessed by subscript directly.
If you need positional access, convert it to a list first.
Example
tinydict
=
{
'Name'
:
'Runoob'
,
'Age'
:
7
,
'Site'
:
'www.runoob.com'
}
values_list
=
list
(
tinydict.
values
(
)
)
(
values_list
)
(
values_list
[
0
]
)
(
values_list
[
1
]
)
Execution result:
['Runoob', 7, 'www.runoob.com']
Runoob
7
Note thatlist() creates a new list. Later additions, removals, or reassignments in the dictionary will not automatically change the corresponding elements in this list.
However, this conversion is a shallow copy: if the values themselves are mutable objects such as lists, the list copy and the dictionary may still reference the same inner objects.
Example 5: dynamic updates of the view object
values() The returned view stays associated with the original dictionary, so when the dictionary changes there is no need to call values()。
Example
dishes
=
{
'eggs'
:
2
,
'sausage'
:
1
,
'bacon'
:
1
,
'spam'
:
500
}
Get the view object
values
=
dishes.
values
(
)
(
list
(
values
)
)
Modify a value in the dictionary
dishes
[
'eggs'
]
=
5
(
list
(
values
)
)
Remove an element from the dictionary
del
dishes
[
'sausage'
]
del
dishes
[
'eggs'
]
(
list
(
values
)
)
Execution result:
[2, 1, 1, 500]
[5, 1, 1, 500]
[1, 500]
As you can see,values always references the dynamic view of the original dictionary.
After the original dictionary is updated, using list(values) again gives the values at that moment.
Example 6: checking whether a value exists
values() Supports using the in operator to check whether a specified value exists in the dictionary.
Example
student
=
{
'name'
:
'Runoob'
,
'age'
:
7
,
'city'
:
'Beijing'
}
(
'Runoob'
in
student.
values
(
)
)
(
'Shanghai'
in
student.
values
(
)
)
(
7
in
student.
values
(
)
)
Execution result:
True
False
True
Note that dictionaries can efficiently check whether a key exists, but looking up a value with values() usually requires comparing values one by one, with time complexity generally O(n).
Example 7: dictionary values may repeat
Dictionary keys must be unique, but different keys may have the same value.
Therefore,values() The returned view may also contain duplicate elements.
Example
scores
=
{
'Tom'
:
90
,
'Jack'
:
85
,
'Lucy'
:
90
,
'Mike'
:
85
}
(
list
(
scores.
values
(
)
)
)
Deduplicate the values
unique_scores
=
set
(
scores.
values
(
)
)
(
sorted
(
unique_scores
)
)
Execution result:
[90, 85, 90, 85]
[85, 90]
To deduplicate the values in a dictionary, you can use set(), but only if the values are hashable.
Example 8: comparing two values() views
Unlike ordinary lists,dict_values views are not compared for equality by their element contents.
Even if two views come from the same dictionary, the comparison result may still be False。
Example
d
=
{
'a'
:
1
}
(
d.
values
(
)
==
d.
values
(
)
)
values
=
d.
values
(
)
(
values
==
values
)
Convert to lists and compare their contents
(
list
(
d.
values
(
)
)
==
list
(
d.
values
(
)
)
)
Execution result:
False
True
True
It is important to distinguish the following cases:
d.values() == d.values(): each call creates a new view object, so the result isFalse。values == values: comparing the same view object with itself givesTrue。list(d.values()) == list(d.values()): compares the element contents of the lists, so the result isTrue。
To check whether two dictionaries have the same key/value pairs, you should usually compare the dictionaries directly rather than comparing values() views.
Differences between values(), keys(), and items()
Python dictionaries provide three commonly used view methods:
| Method | Returns | Example |
|---|---|---|
keys() |
All keys in the dictionary | dict_keys(['a', 'b']) |
values() |
All values in the dictionary | dict_values([1, 2]) |
items() |
All key/value pairs in the dictionary | dict_items([('a', 1), ('b', 2)]) |
For example:
Example
d
=
{
'a'
:
1
,
'b'
:
2
}
(
d.
keys
(
)
)
(
d.
values
(
)
)
(
d.
items
(
)
)
Execution result:
dict_keys(['a', 'b'])
dict_values([1, 2])
dict_items([('a', 1), ('b', 2)])
The views returned by all three methods reflect changes to the original dictionary.
However,keys() views support set-like operations, while values() views are not treated as set-like objects, because dictionary values may repeat.
Notes
- Cannot be accessed directly by index:
d.values()[0]will raiseTypeError。 - **Do not add or remove elements through the view:** operate on the original dictionary and the view will reflect the change automatically.
- **Do not rely on values() for content equality comparisons:** convert to a list first when needed, or use another comparison approach suited to the use case.
- **Avoid adding or removing dictionary elements while iterating:** it may raise
RuntimeErrorand may also result in incomplete iteration. - **Duplicate values allowed:** unlike dictionary keys, values have no uniqueness requirement.
- **Order matches the dictionary:** Python 3.7 and above guarantees values are returned in the insertion order of the keys.
Summary
The Python dictionary's values() The method retrieves all values in a dictionary and returns a dynamic dict_values view object.
It is commonly used for iterating over dictionary values, summing numeric values, checking whether a value exists, and converting dictionary values to a list.
In practice, if you only need to iterate over or read the dictionary's values, you can use values()directly; if you need a list snapshot of the current values, use list(d.values())。
Python3 Dictionary