How to Get a List of Values from a Python Dictionary?

Patricia Arquette
Release: 2024-11-24 20:02:16
Original
172 people have browsed it

How to Get a List of Values from a Python Dictionary?

Retrieving Values from a Dictionary as a List

In Python, a dictionary (dict) stores key-value pairs, where the keys are unique and immutable, and the values can be of any data type. Unlike Java's Map, Python's dict does not have a direct method to retrieve the values as a list.

Solution: Using dict.values()

To obtain a list of values from a dict, you can use the dict.values() method. However, it's important to note that dict.values() returns a view of the dictionary's values rather than a copy. Any changes made to the dict will be reflected in the returned list.

Example:

my_dict = {'a': 1, 'b': 2, 'c': 3}
values_as_list = list(my_dict.values())
print(values_as_list)  # Output: [1, 2, 3]
Copy after login

By wrapping dict.values() in list(), you create a copy of the view, resulting in an immutable list of values. This list can be manipulated independently of the original dict.

The above is the detailed content of How to Get a List of Values from a Python Dictionary?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template