Home >Backend Development >Python Tutorial >How to Extract Dictionary Keys as a List in Python 3?

How to Extract Dictionary Keys as a List in Python 3?

Susan Sarandon
Susan SarandonOriginal
2024-11-26 03:59:16236browse

How to Extract Dictionary Keys as a List in Python 3?

Extracting Keys as a List in Python 3

While in Python 2.7, obtaining dictionary keys as a list was straightforward, Python 3 introduces a change that returns the dict_keys object instead. This alteration can be overcome using list comprehension:

list(newdict.keys())

This method converts the dict_keys object to a regular list.

However, it's important to consider whether using a dict_keys object poses any functional implications. Duck typing in Python allows for objects with similar semantics to be treated as interchangeable. dict_keys behaves like a list in many ways, allowing for iterations and other list-like operations:

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

While dict_keys does not support insertion like dict[k] = v, such operations may not be necessary in many scenarios. By embracing duck typing, you can leverage the functionality of dict_keys without relying on explicit list conversions.

The above is the detailed content of How to Extract Dictionary Keys as a 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