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?