python
Get dictionary values as a list in python
We can get all the values from a dictionary using .values() function. Use list() function to convert it to a list.
companies = {
'tesla': 'Elon Musk',
'meta': 'Mark Zuckerberg',
'amazon': 'Jeff Bezos'
}
company_founders = list(companies.values())
print(company_founders)
# -> ['Elon Musk', 'Mark Zukerberg', 'Jeff Bezos']
We have defined a python dictionary named companies that contains multiple key-value paired items. To get all the values as list items we are using the values() method. It will return all the values as below
dict_values(['Elon Musk', 'Mark Zuckerberg', 'Jeff Bezos'])
To convert the above dict_values to a list we use the list() function.
companies = {
'tesla': 'Elon Musk',
'meta': 'Mark Zukerberg',
'amazon': 'Jeff Bezos'
}
result = []
for key in companies:
result.append(companies[key])
print(result)
# -> ['Elon Musk', 'Mark Zukerberg', 'Jeff Bezos']
We can use Python For Loop also to get all the values for a dictionary as list elements.
Was this helpful?
Similar Posts
- Get all values from a dictionary in Python
- Update dictionary values in python
- Get all values by key name from a list of dictionaries Python
- Get integer only values from a list in Python
- Get the average of List values in Python
- [Python] Using comprehension expression to convert list of dictionaries to nested dictionary
- Sort list and dictionary in python