python

Get all values from a dictionary in Python

If you're looking to get all values from a dictionary in Python, this article is for you. I'll explain how to write a function to get the values, why it works, and how to use it.

# create a dicitonary
user = {
  "first_name": "Sumit",
  "last_name": "Roy",
  "username": "sumit01",
  "email": "[email protected]"
}

# get all the values using Dictionary.values() function
result = list(user.values())

# print the result
print(result)

Output

['Sumit', 'Roy', 'sumit01', '[email protected]']

Get all values from dictionary using Dictionary.values() function

This is the simplest and most pythonic way to extract all the values from a dictionary. We got all the values from a dictionary using the dictionary.values() function and then convert it to Python list using list() function.

# create a dicitonary
student = {
  "id": 1,
  "name": "Joy",
  "course": "Networking",
  "department": "IT",
  "status": "active"
}

# get all the values using Dictionary.values() function
result = list(student.values())

# print the result
print(result)

Output

[1, 'Joy', 'Networking', 'IT', 'active']

In the above code example

  1. Created a dictionary named student that contains multiple key-value pair items.
  2. Using student.values(), we are getting all the values for the dictionary.
  3. Using the list() function we are converting the value to list and now you can access them using the index.

Get all values from a dictionary using Python For Loop

To loop through a dictionary, we can use Python For loop, and in each iteration, we can get the key and value of the dictionary. We will use this to get the values of the dictionary. In order to do it check the below code example.

Code example

# create a dicitonary
student = {
  "id": 1,
  "name": "Joy",
  "course": "Networking",
  "department": "IT",
  "status": "active"
}

result = []

for key in student:
  result.append(student[key])

# print the result
print(result)

Output

[1, 'Joy', 'Networking', 'IT', 'active']
# create a dictionary
nums = {
  1: 10,
  2: 20,
  3: 30,
  4: 40,
  5: 50
}

# get the values list
result = list(nums.values())

# print the result
print(result)

# Output -> [10, 20, 30, 40, 50]
In this code example, we have created a dictionary called nums. Using list(nums.values()), we are getting the values list and printing it.
Was this helpful?