Home > Backend Development > Python Tutorial > How do I get a list of dictionary keys in Python 3?

How do I get a list of dictionary keys in Python 3?

DDD
Release: 2024-11-14 18:30:02
Original
457 people have browsed it

How do I get a list of dictionary keys in Python 3?

Retrieving Dictionary Keys as List in Python

In Python 2.7, obtaining a list of dictionary keys is straightforward:

newdict = {1:0, 2:0, 3:0}
newdict.keys()
Copy after login

However, in Python 3.3 onwards, the output is a "dict_keys" object, not a list:

newdict.keys()
Copy after login

This article explores how to obtain a plain list of keys in Python 3.

Converting dict_keys to List

To convert the dict_keys object to a list, use list comprehension:

list(newdict.keys())
Copy after login

This will produce a list of keys:

[1, 2, 3]
Copy after login

Duck Typing Consideration

However, it's important to consider if converting to a list is necessary. Pythonic principles encourage "duck typing," where objects can be treated as their intended type if they exhibit the correct behavior. In this case, dict_keys can be iterated over like a list:

for key in newdict.keys():
    print(key)
Copy after login

This code will iterate through the keys and print them one by one.

Insertion Considerations

Note that dict_keys does not support insertions, so the following code will not work:

newdict.keys()[0] = 10  # Will result in TypeError
Copy after login

If you require insertion functionality, you should use a list instead of dict_keys.

The above is the detailed content of How do I get a list of dictionary keys in Python 3?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template