Home >Backend Development >Python Tutorial >How to Convert Dict Keys from 'dict_keys' to List in Python 3?

How to Convert Dict Keys from 'dict_keys' to List in Python 3?

DDD
DDDOriginal
2024-11-14 21:51:02979browse

How to Convert Dict Keys from 'dict_keys' to List in Python 3?

Converting Dict Keys from 'dict_keys' to List

In Python 2.7, obtaining dictionary keys as a list was straightforward using newdict.keys(). However, in Python 3.3 and later, this method returns a dict_keys object instead of a list.

To obtain a plain list of keys with Python 3, you can convert the dict_keys object using list(newdict.keys()). This will generate a list of keys that can be manipulated as needed.

Should You Convert?

While converting the dict_keys object to a list is possible, it's worth considering whether it's necessary. In most cases, the dict_keys object behaves similarly to a list. It supports iteration, allowing you to access and process keys efficiently.

For example:

for key in newdict.keys():
    print(key)

The above code will iterate over the keys of the newdict dictionary and print each key.

Extending Dict Keys

It's important to note that the dict_keys object does not support insertion of new keys using newdict[k] = v. If you need to add new keys to your dictionary, use the standard dict methods such as update() or setdefault().

The above is the detailed content of How to Convert Dict Keys from 'dict_keys' to List 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