Python get all values in dict python

How to get a list of all the values from a Python dictionary?

In this article, we’ll show you how to use several ways to extract a list of all the values from a Python dictionary. Using the following methods, we may obtain a list of all the values from a Python dictionary −

  • Using dict.values() & list() functions
  • Using [] and *
  • Using List comprehension
  • Using append() function & For loop

Assume we have taken an example dictionary. We will return the list of all the values from a python dictionary using different methods as specified above.

Method 1: Using dict.values() & list() functions

To obtain the list, we can utilise dictionary.values() in conjunction with the list() function. The values() method is used to access values from the key: value pairs and the values are then converted to a list using the list() function.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the input dictionary
  • Print the list of all the values of a dictionary with the values() function(the dict.values() method provides a view object that displays a list of all the values in the dictionary in order of insertion) by applying it to the input dictionary and convert the result to a list using the list() function(converts the sequence/iterable to a list).
Читайте также:  Swagger ui java maven

Example

The following program returns the size of the list using the len() function −

# input dictionary demoDictionary = 10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'> # Printing the list of values of a dictionary using values() function print(list(demoDictionary.values()))

Output

On executing, the above program will generate the following output −

['TutorialsPoint', 'Python', 'Codes']

Method 2: Using [ ] and *

We may get the entire list of dictionary values by using [] and *. Here, values() is a dictionary method that is used to retrieve the values from the key:value pair in the dictionary, and * is used to get only values rather than dict values, and we then get into a list using the list() function.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the input dictionary.
  • Print the list of all the values of a dictionary with values() function(A view object is returned by the values() method. The dictionary values are stored in the view object as a list), [], * operator.

Example

The following program returns the list of all the values of a dictionary using [] and * operator

# input dictionary demoDictionary = 10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'> # Printing the list of values of a dictionary with values() function # and * operator print([*demoDictionary.values()])

Output

On executing, the above program will generate the following output −

['TutorialsPoint', 'Python', 'Codes']

Method 3: Using List comprehension

To find the list of values, this method uses a list comprehension technique. It accepts a key as input and, using a for loop, returns a list containing the corresponding value for each occurrence of the key in each dictionary in the list. It is more elegant and pythonic when compared to others.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the input dictionary
  • Get all the list of values of the dictionary using the list comprehension by traversing through each value of a dictionary.
demoDictionary[dict_key] represents dictionary value

Example

The following program returns the list of all the values of a dictionary using the List comprehension method −

# input dictionary demoDictionary = 10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'> # Getting the list of values of the dictionary with the list comprehension # demoDictionary[dict_key] represents dictionary value dict_valuesList = [demoDictionary[dict_key] for dict_key in demoDictionary] # Printing the list of all the values of a dictionary print(dict_valuesList)

Output

On executing, the above program will generate the following output −

['TutorialsPoint', 'Python', 'Codes']

Method 4: Using append() function & For loop

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the input dictionary.
  • Create an empty list to store all the keys of an input dictionary.
  • Use the for loop, to traverse through all the values of the dictionary using the values() function(A view object is returned by the values() method. The dictionary values are stored in the view object as a list).
  • Append each value of the dictionary to the list using the append() function(adds the element to the list at the end) by passing the corresponding value as an argument to it.
  • Print the list of all the values in a dictionary.

Example

The following program returns the list of all the values of a dictionary using the append() function & For loop −

# input dictionary demoDictionary = 10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'> # an empty list for storing dictionary values dictValuesList = [] # Traversing through all the values of the dictionary for dictValue in demoDictionary.values(): # appending each value to the list dictValuesList.append(dictValue) # Printing the list of values of a dictionary print(dictValuesList)

Output

On executing, the above program will generate the following output −

['TutorialsPoint', 'Python', 'Codes']

We used an empty list to store the dictionary’s values, then iterated over the values, appended them to the list with the append() function, and displayed them.

Conclusion

This article taught us how to use the values() function to obtain the entire dictionary’s values as well as how to use the list() function to turn the values of the dictionary into a list. Additionally, we learned how to use the list comprehension and for loop in the same code to transform the values from the dictionary returned by the values() method to a list. Finally, we learned how to add elements to a list using the append() function(Here we added values to the list).

Источник

Get Values of a Python Dictionary – With Examples

In this tutorial, we will look at how to get the values of a Python dictionary with the help of some examples.

How to get the values of a dictionary in Python?

get values in a python dictionary

You can use the Python dictionary values() function to get all the values in a Python dictionary. The following is the syntax:

# get all the values in a dictionary sample_dict.values()

It returns a dict_values object containing all the values in the dictionary. This object is iterable, that is, you can use it to iterate through the values in the dictionary. You can use the list() function to convert this object into a list.

Let’s look at some examples.

Using dictionary values() method

Let’s create a dictionary containing the names to department mappings of employees at an office. The keys here are the employee names whereas the values are their respective departments.

Let’s get all the values in the dictionary using the dictionary’s values() function.

# create a dictionary employees = < "Jim": "Sales", "Dwight": "Sales", "Angela": "Accounting" ># get values of dictionary print(employees.values())
dict_values(['Sales', 'Sales', 'Accounting'])

You can see that we get all the names of the departments (the values in the dictionary employee ) in a dict_values object.

Now, you can also convert this object to a list using the Python built-in list() function.

# dictionary values as list print(list(employees.values()))

We now have the values in the dictionary employees as a list.

Using Iteration

Alternatively, you can iterate through the dictionary items and append the value in each iteration to a result list.

# create a dictionary employees = < "Jim": "Sales", "Dwight": "Sales", "Angela": "Accounting" ># get values of dictionary val_ls = [] for key, val in employees.items(): val_ls.append(val) print(val_ls)

We get the values in the dictionary as a list.

You can also reduce the above computation to a single line using list comprehension.

# get values of dictionary val_ls = [val for key, val in employees.items()] print(val_ls)

We get the same result as above.

In this tutorial, we looked at different ways to get all the values in a Python dictionary. Using the dictionary’s values() function is a simpler and a direct way of getting the values as compared to the iteration-based methods.

You might also be interested in –

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Источник

Getting Values from a Dictionary in Python

To access all values in a dictionary in Python, call the values() method.

Or if you want to get a single value, use the square bracket [] access operator:

In case you’re unsure whether the value exists, it makes more sense to use the dict.get() method to access the values. This prevents the program from crashing if the value doesn’t exist.

This is the quick answer. But let’s take a more detailed look at accessing dictionary values in Python.

How to Get All Dictionary Values in Python

If you want to get all the values of a dictionary, use the values() method.

player_data = values = player_data.values()

This returns a dict_keys object. But you can convert it to a list using the list() function:

Now, this list contains all the values from the dictionary (the player numbers):

How to Get a Dictionary Value in Python

Two main ways to get a dictionary value by key in Python

There are two ways to access a single value of a dictionary:

1. Get a Dictionary Value with Square Brackets

Accessing a dictionary value with square brackets in Python

To get a single value from a dictionary, use the square brackets approach.

To do this, place the key whose value you are looking for inside square brackets after the dictionary:

player_data = ronaldo_number = player_data["Ronaldo"] print(ronaldo_number)

The problem with this approach is if there is no such key-value pair in the dictionary, an error is thrown and your program crashes.

For instance, let’s try to get a number of a player that does not exist:

player_data = rivaldo_number = player_data.get("Rivaldo") print(rivaldo_number)

To overcome this issue, use the get() method to get a value from a dictionary instead.

2. Python Dictionary get() Method

Accessing python dictionary values with the get method

In addition to using square brackets to access dictionary values in Python, you can use the get() method.

To do this, enter the key whose value you are searching for inside the get() method.

player_data = ronaldo_number = player_data.get("Ronaldo") print(ronaldo_number)

Now if you try to access a non-existent value from the dictionary, you get a None back. This is better as your program does not crash even the value you are looking for is not there:

player_data = rivaldo_number = player_data.get("Rivaldo") print(rivaldo_number)

Conclusion

To access a dictionary value in Python you have three options:

  1. Use the dictionary.values() method to get all the values
  2. Use the square brackets [] to get a single value (unsafely).
  3. Use the dictionary.get() method to safely get a single value from a dictionary.

Using get() is safe because it returns None if the value is not found. Using square brackets crashes your program if the value is not found.

Thanks for reading. I hope you found the values you were looking for. Happy coding!

Further Reading

Источник

Оцените статью