Home  >  Article  >  Backend Development  >  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
DDDOriginal
2024-11-14 18:30:02381browse

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()

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

newdict.keys()

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())

This will produce a list of keys:

[1, 2, 3]

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)

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

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!

Statement:
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