{"id":87,"date":"2024-01-25T10:00:39","date_gmt":"2024-01-25T10:00:39","guid":{"rendered":"https:\/\/learnpython.elegantwallp.com\/?p=87"},"modified":"2024-01-25T10:00:40","modified_gmt":"2024-01-25T10:00:40","slug":"python-dictionary","status":"publish","type":"post","link":"https:\/\/learnpython.elegantwallp.com\/2024\/01\/25\/python-dictionary\/","title":{"rendered":"Python Dictionary"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you\u2019ll learn about Python Dictionary which allows you to organize related information.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the Python Dictionary type<\/h2>\n\n\n\n<p>A Python dictionary is a collection of key-value pairs where each key is associated with a value.<\/p>\n\n\n\n<p>A value in the key-value pair can be a\u00a0number, a\u00a0string, a\u00a0list, a\u00a0tuple, or even another dictionary. In fact, you can use a value of any valid type in Python as the value in the key-value pair.<\/p>\n\n\n\n<p>A key in the key-value pair must be immutable. In other words, the key cannot be changed, for example, a number, a string, a tuple, etc.<\/p>\n\n\n\n<p>Python uses curly braces&nbsp;<code>{}<\/code>&nbsp;to define a dictionary. Inside the curly braces, you can place zero, one, or many key-value pairs.<\/p>\n\n\n\n<p>The following example defines an empty dictionary:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>empty_dict = {}<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Typically, you define an empty dictionary before a loop, either\u00a0for loop\u00a0or\u00a0while loop. And inside the loop, you add key-value pairs to the dictionary.<\/p>\n\n\n\n<p>To find the type of a dictionary, you use the\u00a0<code>type()<\/code>\u00a0function as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>empty_dict = {} print(type(empty_dict)) <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>&lt;class 'dict'><\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The following example defines a dictionary with some key-value pairs:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 25, 'favorite_colors': &#91;'blue', 'green'], 'active': True } <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The&nbsp;<code>person<\/code>&nbsp;dictionary has five key-value pairs that represent the first name, last name, age, favorite colors, and active status.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Accessing values in a Dictionary<\/h2>\n\n\n\n<p>To access a value by key from a dictionary, you can use the square bracket notation or the&nbsp;<code>get()<\/code>&nbsp;method.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1) Using square bracket notation<\/h3>\n\n\n\n<p>To access a value associated with a key, you place the key inside square brackets:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>dict&#91;key]<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The following shows how to get the values associated with the key\u00a0<code>first_name<\/code>\u00a0and\u00a0<code>last_name<\/code>\u00a0in the\u00a0<code>person<\/code>\u00a0dictionary:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 25, 'favorite_colors': &#91;'blue', 'green'], 'active': True } print(person&#91;'first_name']) print(person&#91;'last_name'])<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>John Doe<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">2) Using the get() method<\/h3>\n\n\n\n<p>If you attempt to access a key that doesn\u2019t exist, you\u2019ll get an error. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 25, 'favorite_colors': &#91;'blue', 'green'], 'active': True } ssn = person&#91;'ssn']<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Error:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>Traceback (most recent call last): File \"dictionary.py\", line 15, in &lt;module> ssn = person&#91;'ssn'] KeyError: 'ssn'<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>To avoid this error, you can use the\u00a0<code>get()<\/code>\u00a0method of the dictionary:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 25, 'favorite_colors': &#91;'blue', 'green'], 'active': True } ssn = person.get('ssn') print(ssn) <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>None<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>If the key doesn\u2019t exist, the&nbsp;<code>get()<\/code>&nbsp;method returns&nbsp;<code>None<\/code>&nbsp;instead of throwing a&nbsp;<code>KeyError<\/code>. Note that&nbsp;<code>None<\/code>&nbsp;means no value exists.<\/p>\n\n\n\n<p>The&nbsp;<code>get()<\/code>&nbsp;method also returns a default value when the key doesn\u2019t exist by passing the default value to its second argument.<\/p>\n\n\n\n<p>The following example returns the\u00a0<code>'000-00-0000'<\/code>\u00a0string if the\u00a0<code>ssn<\/code>\u00a0key doesn\u2019t exist in the\u00a0<code>person<\/code>\u00a0dictionary:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 25, 'favorite_colors': &#91;'blue', 'green'], 'active': True } ssn = person.get('ssn', '000-00-0000') print(ssn)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>000-00-0000<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Adding new key-value pairs<\/h2>\n\n\n\n<p>Since a dictionary has a dynamic structure, you can add new key-value pairs to it at any time.<\/p>\n\n\n\n<p>To add a new key-value pair to a dictionary, you specify the name of the dictionary followed by the new key in square brackets along with the new value.<\/p>\n\n\n\n<p>The following example adds a new key-value pair to the\u00a0<code>person<\/code>\u00a0dictionary:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person&#91;'gender'] = 'Famale' <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Modifying values in a key-value pair<\/h2>\n\n\n\n<p>To modify a value associated with a key, you specify the dictionary name with the key in square brackets and the new value associated with the key:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>dict&#91;key] = new_value<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The following example modifies the value associated with the\u00a0<code>age<\/code>\u00a0of the\u00a0<code>person<\/code>\u00a0dictionary:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 25, 'favorite_colors': &#91;'blue', 'green'], 'active': True } person&#91;'age'] = 26 print(person)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>{'first_name': 'John', 'last_name': 'Doe', 'age': 26, 'favorite_colors': &#91;'blue', 'green'], 'active': True}<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Removing key-value pairs<\/h2>\n\n\n\n<p>To remove a key-value pair by a key, you use the\u00a0<code>del<\/code>\u00a0statement:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>del dict&#91;key]<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>In this syntax, you specify the dictionary name and the key that you want to remove.<\/p>\n\n\n\n<p>The following example removes the key\u00a0<code>'active'<\/code>\u00a0from the\u00a0<code>person<\/code>\u00a0dictionary:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 25, 'favorite_colors': &#91;'blue', 'green'], 'active': True } del person&#91;'active'] print(person)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>{'first_name': 'John', 'last_name': 'Doe', 'age': 25, 'favorite_colors': &#91;'blue', 'green']}<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Looping through a dictionary<\/h2>\n\n\n\n<p>To examine a dictionary, you can use a&nbsp;<code>for<\/code>&nbsp;loop to iterate over its key-value pairs, or keys, or values.<\/p>\n\n\n\n<p>Note that since Python 3.7, when you loop through a dictionary, you\u2019ll get the key-value pairs in the same order that you insert them.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1) Looping all key-value pairs in a dictionary<\/h3>\n\n\n\n<p>Python dictionary provides a method called&nbsp;<code>items()<\/code>&nbsp;that returns an object which contains a list of key-value pairs as tuples in a list.<\/p>\n\n\n\n<p>For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 25, 'favorite_colors': &#91;'blue', 'green'], 'active': True } print(person.items())<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>dict_items(&#91;('first_name', 'John'), ('last_name', 'Doe'), ('age', 25), ('favorite_colors', &#91;'blue', 'green']), ('active', True)])<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>To iterate over all key-value pairs in a dictionary, you use a\u00a0<code>for<\/code>\u00a0loop with two variable\u00a0<code>key<\/code>\u00a0and\u00a0<code>value<\/code>\u00a0to\u00a0unpack each tuple\u00a0of the list:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 25, 'favorite_colors': &#91;'blue', 'green'], 'active': True } for key, value in person.items(): print(f\"{key}: {value}\")<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>first_name: John last_name: Doe age: 25 favorite_colors: &#91;'blue', 'green'] active: True<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Note that you can use any variable name in the&nbsp;<code>for<\/code>&nbsp;loop. They don\u2019t have to be the&nbsp;<code>key<\/code>&nbsp;and&nbsp;<code>value<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2) Looping through all the keys in a dictionary<\/h3>\n\n\n\n<p>Sometimes, you just want to loop through all keys in a dictionary. In this case, you can use a&nbsp;<code>for<\/code>&nbsp;loop with the&nbsp;<code>keys()<\/code>&nbsp;method.<\/p>\n\n\n\n<p>The&nbsp;<code>keys()<\/code>&nbsp;method returns an object that contains a list of keys in the dictionary.<\/p>\n\n\n\n<p>For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code> person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 25, 'favorite_colors': &#91;'blue', 'green'], 'active': True } for key in person.keys(): print(key)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>first_name last_name age favorite_colors active<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>In fact, looping through all keys is the default behavior when looping through a dictionary. Therefore, you don\u2019t need to use the&nbsp;<code>keys()<\/code>&nbsp;method.<\/p>\n\n\n\n<p>The following code returns the same output as the one in the above example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 25, 'favorite_colors': &#91;'blue', 'green'], 'active': True } for key in person: print(key)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">3) Looping through all the values in a dictionary<\/h3>\n\n\n\n<p>The&nbsp;<code>values()<\/code>&nbsp;method returns a list of values without any keys.<\/p>\n\n\n\n<p>To loop through all the values in a dictionary, you use a for loop with the\u00a0<code>values()<\/code>\u00a0method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 25, 'favorite_colors': &#91;'blue', 'green'], 'active': True } for value in person.values(): print(value) <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>John Doe 25 &#91;'blue', 'green'] True<\/code><\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you\u2019ll learn about Python Dictionary which allows you to organize related information. Introduction to the Python Dictionary type A Python dictionary is a collection of key-value pairs where each key is associated with a value. A value in the key-value pair can be a\u00a0number, a\u00a0string, a\u00a0list, a\u00a0tuple, or even another dictionary. [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[20],"tags":[],"class_list":["post-87","post","type-post","status-publish","format-standard","hentry","category-6-dictionaries"],"_links":{"self":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/87","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/comments?post=87"}],"version-history":[{"count":1,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/87\/revisions"}],"predecessor-version":[{"id":88,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/87\/revisions\/88"}],"wp:attachment":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/media?parent=87"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/categories?post=87"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/tags?post=87"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}