{"id":8149,"date":"2023-07-24T16:00:04","date_gmt":"2023-07-24T10:30:04","guid":{"rendered":"https:\/\/tutorpython.com\/?p=8149"},"modified":"2023-10-19T15:16:45","modified_gmt":"2023-10-19T09:46:45","slug":"dict_values-object-is-not-subscriptable","status":"publish","type":"post","link":"https:\/\/tutorpython.com\/dict_values-object-is-not-subscriptable","title":{"rendered":"Python &#8216;dict_values&#8217; object is not subscriptable"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-transparent ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">In This Article<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/tutorpython.com\/dict_values-object-is-not-subscriptable\/#The_dict_values_Object\" >The dict_values Object<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/tutorpython.com\/dict_values-object-is-not-subscriptable\/#Subscriptable_Objects_in_Python\" >Subscriptable Objects in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/tutorpython.com\/dict_values-object-is-not-subscriptable\/#Some_Solutions_to_this_Error\" >Some Solutions to this Error<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/tutorpython.com\/dict_values-object-is-not-subscriptable\/#Iterating_over_dict_values\" >Iterating over dict_values<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/tutorpython.com\/dict_values-object-is-not-subscriptable\/#Converting_dict_values_to_other_subscriptable_objects\" >Converting dict_values to other subscriptable objects<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/tutorpython.com\/dict_values-object-is-not-subscriptable\/#Utilizing_dictionary_methods_to_access_elements\" >Utilizing dictionary methods to access elements<\/a><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n<p>While working with <a href=\"https:\/\/tutorpython.com\/tutorial\/dictionaries-in-python\" target=\"_blank\" rel=\"noopener\">Python dictionaries<\/a>, we might encounter the following error: <code>\"TypeError: 'dict_values' object is not subscriptable.\"<\/code>. If you&#8217;ve faced this error or want to ensure you never stumble upon it, you&#8217;ve come to the right place.<\/p>\n<p>In this article, we will discuss the <code>dict_values<\/code>object and then uncover why the programmer could encounter the error. By the end of this article, you will gain a better understanding of why the error occurs, and how to avoid running into it. So, let us start our exploration.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"The_dict_values_Object\"><\/span>The <code>dict_values<\/code> Object<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>A Python dictionary stores data as key-value pairs. In order to access all values in a dictionary at once, the dictionary object provides the <code>values()<\/code> method. The <code>values()<\/code> method, when called, returns a <code>dict_values<\/code> object that represents all the values contained within the dictionary.<\/p>\n<p>The <code>dict_values<\/code> object is iterable that provides access to all values in the dictionary. Also, any changes in the dictionary, like adding a new key-value pair, will be reflected in the <code>dict_values<\/code> object. The <code>dict_values<\/code> object provides a way to access the dictionary&#8217;s values without the need for the associated keys.<\/p>\n<p>The code example below defines a dictionary object and accesses the <code>dict_values<\/code> object.<\/p>\n<pre class=\"language-python line-numbers\"><code># Create a dictionary containing student scores\r\nstudent_scores = {'Alice': 85, 'Bob': 72, 'Charlie': 90, 'David': 78}\r\n\r\n# Get the 'dict_values' object using the .values() method\r\nscores_values = student_scores.values()\r\n\r\n# Output the 'dict_values' object\r\nprint(scores_values)  # Output: dict_values([85, 72, 90, 78])\r\n\r\n# Loop through the 'dict_values' object\r\nfor score in scores_values:\r\n    print(score)  # Output: 85, 72, 90, 78\r\n<\/code><\/pre>\n<p>The output is shown below:<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-8552\" src=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_dict_values_example.jpg\" alt=\"output for getting dict_values from dict.values() method\" width=\"360\" height=\"101\" srcset=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_dict_values_example.jpg 360w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_dict_values_example-300x84.jpg 300w\" sizes=\"(max-width: 360px) 100vw, 360px\" \/><\/p>\n<p>As can be seen from the output, the first call to <code>print<\/code>returns the <code>dict_values<\/code> iterable. Within the <code>for<\/code> loop, however, the <code>dict_values<\/code>object is iterated over so as to allow access to individual values in the iterable. As each value is accessed, we print it to the console.<\/p>\n<p>The next code example demonstrated the dynamic nature of the <code>dict_values<\/code> object.<\/p>\n<pre class=\"language-python line-numbers\"><code># Adding a new key-value pair to the dictionary\r\nstudent_scores['Eve'] = 95\r\n\r\n# Output the 'dict_values' object after adding a new entry\r\nprint(scores_values)  # Output: dict_values([85, 72, 90, 78, 95])\r\n\r\n# Removing a key-value pair from the dictionary\r\ndel student_scores['Charlie']\r\n\r\n# Output the 'dict_values' object after removing an entry\r\nprint(scores_values)  # Output: dict_values([85, 72, 78, 95])\r\n<\/code><\/pre>\n<p>The first change made to the dictionary was to add the new key-value pair <code>\"Eve\": 95<\/code>. The <code>dict_values<\/code> object referenced by the <code>score_values<\/code> variable is updated to reflect this change (as seen in the output within the comment).<\/p>\n<p>The second change made was to delete the key-value pair <code>\"Charlie\":\u00a0 90<\/code>. The output also show that the delete change was also reflected in the <code>dict_values<\/code> output.<\/p>\n<p>However, unlike lists, or tuples, the <code>dict_values<\/code> object does not support indexing or slicing. This is because it is a dynamic view of the dictionary&#8217;s current state.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Subscriptable_Objects_in_Python\"><\/span>Subscriptable Objects in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Subscriptable objects allow us to make use of square brackets <code>[]<\/code> to access individual elements within the object. \u00a0With this feature, we can access items by index\/position, or by key.<\/p>\n<p>An example of a subscriptable object is a list. Items in a list can be accessed by index by utilizing the <code>[]<\/code> notation and including the position\/index of the object in between the square brackets. See the code example below:<\/p>\n<pre class=\"language-python line-numbers\"><code>my_list = [10, 20, 30, 40]\r\nprint(my_list[0])  # Output: 10\r\n<\/code><\/pre>\n<p>While a list is subscriptable (also tuples, and strings), any object of the type <code>dict_values<\/code> is not subscriptable, and thus, does not allow direct access to the elements within them. See the code example below of an attempt to access elements in a <code>dict_value<\/code> object by subscripting:<\/p>\n<pre class=\"language-python line-numbers\"><code>student_scores = {'Alice': 85, 'Bob': 72, 'Charlie': 90}\r\nscores_values = student_scores.values()\r\n\r\n# The following line will raise a TypeError\r\nprint(scores_values[0])\r\n<\/code><\/pre>\n<p>The output we get is shown below:<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-8557\" src=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/error_dict_values_not_subscrptable.jpg\" alt=\"typeerror dict_values object not subscriptable\" width=\"594\" height=\"158\" srcset=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/error_dict_values_not_subscrptable.jpg 594w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/error_dict_values_not_subscrptable-300x80.jpg 300w\" sizes=\"(max-width: 594px) 100vw, 594px\" \/><\/p>\n<p>As seen from the error message, we cannot directly access individual items inside the <code>dict_values<\/code> object by making use of indexing\/subscripting.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Some_Solutions_to_this_Error\"><\/span>Some Solutions to this Error<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>In order to circumvent this error that arises when we try to access a <code>dict_values<\/code> object by indexing, we need to understand that a <code>dict_values<\/code> object is not subscriptable like a list, or string. Instead of trying to directly access the items in a <code>dict_values<\/code> object, we can make use of alternative approaches. Some of them will be discussed in the subsections that follow.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Iterating_over_dict_values\"><\/span>Iterating over <code>dict_values<\/code><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Since the <code>dict_values<\/code> object is iterable, we can use the <code>for<\/code> loop to iterate over each dictionary value it references. Let us see this in action in the code snippet below:<\/p>\n<pre class=\"language-python line-numbers\"><code>student_scores = {'Alice': 85, 'Bob': 72, 'Charlie': 90}\r\nscores_values = student_scores.values()\r\n\r\n# Using a for loop to iterate over 'dict_values'\r\nfor score in scores_values:\r\n    print(score)\r\n<\/code><\/pre>\n<p>This approach successfully accesses each value referenced by the <code>dict_value<\/code> object as seen in the output below.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-8561\" src=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_dict_values_for_loop.jpg\" alt=\"using for loop to iterate over dict_values\" width=\"493\" height=\"68\" srcset=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_dict_values_for_loop.jpg 493w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_dict_values_for_loop-300x41.jpg 300w\" sizes=\"(max-width: 493px) 100vw, 493px\" \/><\/p>\n<h3><span class=\"ez-toc-section\" id=\"Converting_dict_values_to_other_subscriptable_objects\"><\/span>Converting <code>dict_values<\/code> to other subscriptable objects<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>We might have a specific use case that requires that we make use of indexing. If this situation arises, we will need to convert the <code>dict_values<\/code> object into a subscriptable object, like a list, or tuple. Then we use the <code>[]<\/code> notation to access the values individually. See an example in the code snippet below.<\/p>\n<pre class=\"language-python line-numbers\"><code>student_scores = {'Alice': 85, 'Bob': 72, 'Charlie': 90}\r\nscores_values = student_scores.values()\r\n\r\n# Convert 'dict_values' to a list\r\nscores_list = list(scores_values)\r\n\r\n# Accessing elements using index\r\nprint(scores_list[1])  # Output: 72\r\n<\/code><\/pre>\n<p>We have to note, however, that this conversion will create a separate copy of the dictionary values in the list. As a result, any changes to the underlying dictionary will not be reflected in the newly created list of dictionary values.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Utilizing_dictionary_methods_to_access_elements\"><\/span>Utilizing dictionary methods to access elements<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>There are several built-in methods provided by Python dictionaries to access the contents of a dictionary. One of them is the <code>get()<\/code> method. the example below illustrates how to make use of the <code>get()<\/code> method to access values within a dictionary.<\/p>\n<pre class=\"language-python line-numbers\"><code>student_scores = {'Alice': 85, 'Bob': 72, 'Charlie': 90}\r\n\r\n# Using .get() method to retrieve a specific value\r\nalice_score = student_scores.get('Alice')\r\nprint(alice_score)  # Output: 85<\/code><\/pre>\n<p>The code makes use of the <code>get()<\/code> method to directly access the value associated with the dictionary key <code>'Alice'<\/code>. The attempt successfully retrieves that value <code>85<\/code> without the error occurring.<\/p>\n<p>To conclude, in order to avoid running into the error <code>'TypeError: 'dict_values' object is not subscriptable'<\/code>, we need to appreciate that the <code>dict_values<\/code> object in Python is iterable that does allow indexing. However, there are ways we could circumvent this error, which we have covered in this article.<\/p>\n<p>If you liked this article, you are welcome to explore our <a href=\"https:\/\/tutorpython.com\/blog\" target=\"_blank\" rel=\"noopener\">knowledgebase of Python<\/a> articles that can assist you in learning more about Python and becoming a more proficient developer. In the meantime, Happy coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>While working with Python dictionaries, we might encounter the following error: &#8220;TypeError:&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[28],"tags":[],"class_list":["post-8149","post","type-post","status-publish","format-standard","hentry","category-tutorial"],"acf":[],"_links":{"self":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/8149","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/comments?post=8149"}],"version-history":[{"count":19,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/8149\/revisions"}],"predecessor-version":[{"id":8569,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/8149\/revisions\/8569"}],"wp:attachment":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/media?parent=8149"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/categories?post=8149"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/tags?post=8149"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}