Python return values from dictionary

Python dict.values()

In this article we will discuss how to use values() function of dict class in python and then we will see several examples of the values() function.

dict.values() Syntax:

In python, the dict class provides a member function to fetch all values from dictionary i.e.

Return Value:

Frequently Asked:

      • It returns a sequence containing the view of all values from the dictionary. If any value gets modified in the dictionary then it will be reflected in sequence too, because that is just a view of values.

      Let’s understand with some examples,

      Examples of dict.values() in python

      Get all values from a dictionary in python

      # Dictionary of string and int word_freq = < "Hello": 56, "at": 23, "test": 43, "this": 78, 'hi': 99 ># Get all values from a dictionary in python values = word_freq.values() print(values)
      dict_values([56, 23, 43, 78, 99])

      values() function returned a sequence dict_values, it contains the view of all values in the dictionary.

      We can also iterate over the sequence and access each value one by one,

      print('Iterate over all values') for elem in word_freq.values(): print(elem)
      Iterate over all values 56 23 43 78 99

      Effect of Dictionary modification on returned values

      If we first fetch all the values of the dictionary using values() function and then modify the dictionary, then changes will be reflected in the sequence of the already fetched values too. For example,

      # Dictionary of string and int word_freq = < "Hello": 56, "at": 23, "test": 43, "this": 78, 'hi': 99 ># Get all values from a dictionary in python values = word_freq.values() print('Values of dictionary: ') print(values) # Modify the value of a key, it will modify the values # in already fetched sequence too word_freq['at'] = 200 print('Values of dictionary: ') print(values)
      Values of dictionary: dict_values([56, 23, 43, 78, 99]) Values of dictionary: dict_values([56, 200, 43, 78, 99])

      Here we created a sequence of values from the dictionary and then we modified the value of key ‘at’ in the dictionary. Now the value of key ‘at’ is also updated in the sequence of the values, which we got from the values() function, because values() method always returns a view of all values in the dictionary.

      But now suppose we don’t want the view, what if we want a copy of all values in the dictionary?

      We can do that by converting all values of the dictionary to a list,

      Convert values of a dictionary to a list

      To create a list of all values in the dictionary we can pass the sequence returned by values() function to the list() i.e.

      # Dictionary of string and int word_freq = < "Hello": 56, "at": 23, "test": 43, "this": 78, 'hi': 99 ># convert all values in dictionary to a list list_of_values = list( word_freq.values() ) print('Values of Dictionary: ') print(list_of_values)
      Values of Dictionary: [56, 23, 43, 78, 99]

      It returned a list of all values in the dictionary. The list contains a copy of the values in the dictionary. It means if we modify the value of any key in the dictionary then it will not update the list of values. For example,

      # Modify the value of a key word_freq['at'] = 200 print('Values of Dictionary: ') print(list_of_values)
      Values of Dictionary: [56, 23, 43, 78, 99]

      We modified the value of key ’at’, but the changes are not reflected in the already created values list, because it contains the copy of values not the view.

      Get the sum of dictionary values in python

      As values() function returns a sequence of values of the dictionary, so we can pass this sequence to the sum() function to get the sum of all values of the dictionary. For example,

      # Dictionary of string and int word_freq = < "Hello": 56, "at": 23, "test": 43, "this": 78, 'hi': 99 ># python dictionary values sum sum_of_values = sum(word_freq.values()) print('Sum of Values: ', sum_of_values)

      Get average of dictionary values in python

      To get the average of all values in the dictionary, just divide the sum of values by the size of the dictionary. For example,

      # Dictionary of string and int word_freq = < "Hello": 56, "at": 23, "test": 43, "this": 78, 'hi': 99 ># python dictionary values average avg_of_values = sum(word_freq.values()) / len(word_freq.values()) print('Average of values: ', avg_of_values)

      So, this is how we can use the values() method of dict class.

      Share your love

      Leave a Comment Cancel Reply

      This site uses Akismet to reduce spam. Learn how your comment data is processed.

      Terms of Use

      Disclaimer

      Copyright © 2023 thisPointer

      To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

      Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

      The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

      The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

      The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

      The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

      Источник

      Get value from dictionary by key with get() in Python

      This article describes how to get the value from a dictionary ( dict type object) by the key in Python.

      If you want to extract keys by their values, see the following article.

      Get value from dictionary with dictPython return values from dictionary ( KeyError for non-existent keys)

      In Python, you can get the value from a dictionary by specifying the key like dictPython return values from dictionary .

      d = 'key1': 'val1', 'key2': 'val2', 'key3': 'val3'> print(d['key1']) # val1 

      In this case, KeyError is raised if the key does not exist.

      # print(d['key4']) # KeyError: 'key4' 

      Specifying a non-existent key is not a problem if you want to add a new element.

      For more information about adding items to the dictionary, see the following article.

      Use in to check if the key exists in the dictionary.

      Use dict.get() to get the default value for non-existent keys

      You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist.

      Specify the key as the first argument. If the key exists, the corresponding value is returned; otherwise, None is returned.

      d = 'key1': 'val1', 'key2': 'val2', 'key3': 'val3'> print(d.get('key1')) # val1 print(d.get('key4')) # None 

      You can specify the default value to be returned when the key does not exist in the second argument.

      print(d.get('key4', 'NO KEY')) # NO KEY print(d.get('key4', 100)) # 100 

      The original dictionary remains unchanged.

      Источник

      Get value from dictionary by key with get() in Python

      This article describes how to get the value from a dictionary ( dict type object) by the key in Python.

      If you want to extract keys by their values, see the following article.

      Get value from dictionary with dictPython return values from dictionary ( KeyError for non-existent keys)

      In Python, you can get the value from a dictionary by specifying the key like dictPython return values from dictionary .

      d = 'key1': 'val1', 'key2': 'val2', 'key3': 'val3'> print(d['key1']) # val1 

      In this case, KeyError is raised if the key does not exist.

      # print(d['key4']) # KeyError: 'key4' 

      Specifying a non-existent key is not a problem if you want to add a new element.

      For more information about adding items to the dictionary, see the following article.

      Use in to check if the key exists in the dictionary.

      Use dict.get() to get the default value for non-existent keys

      You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist.

      Specify the key as the first argument. If the key exists, the corresponding value is returned; otherwise, None is returned.

      d = 'key1': 'val1', 'key2': 'val2', 'key3': 'val3'> print(d.get('key1')) # val1 print(d.get('key4')) # None 

      You can specify the default value to be returned when the key does not exist in the second argument.

      print(d.get('key4', 'NO KEY')) # NO KEY print(d.get('key4', 100)) # 100 

      The original dictionary remains unchanged.

      Источник

      Читайте также:  Функция определения длины строки php
Оцените статью