How can to get list of values from dictionary in Python?
Published on Aug. 22, 2023, 12:15 p.m.
To get a list of values from a dictionary in Python
To get a list of values from a dictionary in Python, you can use the values()
function. Here’s an example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
values_list = list(my_dict.values())
print(values_list)
Output:
[1, 2, 3]
In this example, we define a dictionary my_dict
with key-value pairs. We then use the values()
function to obtain a list of values from the dictionary, and convert it to a list using the list()
function. Finally, we print the resulting list values_list
.
To iterate over the keys and values in a dictionary in Python
To iterate over the keys and values in a dictionary in Python, you can use the items()
method. Here’s an example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")
Output:
Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3
In this example, we define a dictionary my_dict
with key-value pairs. We then use a for
loop to iterate over each key-value pair in the dictionary, utilizing the items()
method to return an iterable of the key-value pairs as tuples. The key, value
notation used in the loop assigns the key and value to separate variables. Finally, we print out the keys and values for each iteration.