Python3 Dictionary keys() Method
Description
The Python3 dictionary keys() method returns a view object.
dict.keys()、dict.values() and dict.items() The return value is a view object, which provides a dynamic view of the dictionary's entries; this means the view changes along with the dictionary.
A view object is not a list and does not support indexing; use list() to convert it to a list.
We cannot make any modifications to view objects, because dictionary view objects are read-only.
**Note:** Python 2.x returned a list directly
Syntax
keys() method syntax:
dict.keys()
Parameters
- NA。
Return Value
Returns a view object.
Example
The following example shows how to use the keys() method:
Example
dishes
=
{
'eggs'
:
2
,
'sausage'
:
1
,
'bacon'
:
1
,
'spam'
:
500
}
keys
=
dishes.
keys
(
)
values
=
dishes.
values
(
)
Iterate
n
=
0
for
val
in
values:
...
n
=
val
(
n
)
504
keys and values are iterated in the same order (insertion order)
list
(
keys
)
Convert to a list using list()
[
'eggs'
,
'sausage'
,
'bacon'
,
'spam'
]
list
(
values
)
[
2
,
1
,
1
,
500
]
View objects are dynamic and affected by dictionary changes; below, after a key is deleted, the view converted to a list changes too
del
dishes
[
'eggs'
]
del
dishes
[
'sausage'
]
list
(
keys
)
[
'bacon'
,
'spam'
]
Python3 Dictionary