<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ dictionary - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ dictionary - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 29 May 2026 23:04:24 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/dictionary/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use DefaultDict in Python ]]>
                </title>
                <description>
                    <![CDATA[ By Gage Schaffer Throughout my time working with datasets in Python, the dictionary has been my most used data structure. It’s versatile and easy to use. Need to count occurrences of a character? Use a dictionary! Want to create a list of soccer play... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-defaultdict-python/</link>
                <guid isPermaLink="false">66d45eddaad1510d0766b611</guid>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 01 May 2024 21:15:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/05/Add-To-Your-Python-Toolbox.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Gage Schaffer</p>
<p>Throughout my time working with datasets in Python, the dictionary has been my most used data structure. It’s versatile and easy to use.</p>
<p>Need to count occurrences of a character? Use a dictionary!</p>
<p>Want to create a list of soccer players and associated stats? Dictionary!</p>
<p>They’re not fool-proof, though. In many tasks, you’ll run into KeyErrors galore when grokking data, which can be frustrating to deal with. </p>
<p>Dealing with these errors results in several extra lines of code. This reduces readability and increases complexity. If you’re handling a lot of data, this problem can spiral out of control.</p>
<p>The collections module addresses this problem of complexity. The collections module is a part of the Python standard library which contains a few awesome ways to wrangle data. The primary goal of the module is to make your code more readable and to simplify data processing with some extra types.</p>
<p>The one that I use the most is <code>defaultdict</code>, and we’ll explore some simple use cases for that today. To fully appreciate this data container, you should have a working knowledge of Python. More specifically, the regular dictionary type.</p>
<h2 id="heading-how-to-simplify-your-code-with-the-defaultdict">How to Simplify Your Code with the DefaultDict</h2>
<p>Before we get into today’s topic, let’s look at a situation. I want to create a dictionary that gives me the count of all the different letters in the word “Mississippi”. There are a lot of S’s and P’s, and I don’t have the time to count them all by hand.</p>
<p>Here’s how I would do that using a standard dictionary:</p>
<pre><code class="lang-python">letters = {}

<span class="hljs-keyword">for</span> letter <span class="hljs-keyword">in</span> <span class="hljs-string">"Mississippi"</span>:
    <span class="hljs-keyword">if</span> letter <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> letters:
        letters[letter] = <span class="hljs-number">1</span>
    <span class="hljs-keyword">else</span>:
        letters[letter] +=<span class="hljs-number">1</span>

print(letters)
<span class="hljs-comment"># {'M': 1, 'i': 4, 's': 4, 'p': 2}</span>
</code></pre>
<p>Simple enough. This program:</p>
<ul>
<li>Iterated through the string. </li>
<li>Each iteration, it checked if the letter currently had an entry into our letters dictionary. </li>
<li>If the letter is present, it adds one to the current value. </li>
<li>If the letter is not present in the letters dictionary, it creates the entry and sets the initial value to 1.</li>
</ul>
<p>This example was pretty easy, but you can see the code complexity creeping in already. Let’s see how we can do better:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> defaultdict

letters = defaultdict(int)

<span class="hljs-keyword">for</span> letter <span class="hljs-keyword">in</span> <span class="hljs-string">"Mississippi"</span>:
    letters[letter] += <span class="hljs-number">1</span>

print(letters)
<span class="hljs-comment"># defaultdict(&lt;class 'int'&gt;, {'M': 1, 'i': 4, 's': 4, 'p': 2})</span>
</code></pre>
<p>You should notice that all the conditional statements are now gone. The code should be a little easier to read, but we still got the same result at the end of the program.</p>
<p>This is the benefit of <code>defaultdict</code>. Let’s break this data container down.</p>
<h3 id="heading-exploring-the-defaultdict-data-container">Exploring the DefaultDict Data Container</h3>
<p>The idea of a <code>defaultdict</code> is simple: if we attempt to access or change the value of a key that does not exist, it creates the entry in the dictionary with the given default value.</p>
<p>In the above example, we started with an empty defaultdict with no entries. For each unique letter we parsed, the dictionary created an entry. Since we used <code>int</code> as the default value, the value of the created entry was 0. After the dictionary created the entry, it added one to the entry.</p>
<p>At the end of the program, the letter count was output without conditionals or manual intervention. Very Pythonic.</p>
<h3 id="heading-how-to-set-the-default-in-defaultdict">How to Set the Default in DefaultDict</h3>
<p>The <code>defaultdict</code> data container takes a single argument during its initialization, named <code>default_factory</code>.</p>
<p>This <code>default_factory</code> argument is a function. When the program attempts to access an entry that does not exist, the <code>defaultdict</code> calls the <code>default_factory</code> without any arguments. So, for example, I can call a <code>defaultdict</code> with the function <code>int()</code> like this:</p>
<pre><code class="lang-python">d1 = defaultdict(int)
</code></pre>
<p>When I attempt to access an entry that does not exist, it’ll append that entry with the value of the <code>int</code> function, which is 0.</p>
<pre><code class="lang-python">d1 = defaultdict(int)

d1[“Adding an entry!”]

Print(d1)
<span class="hljs-comment"># defaultdict(&lt;class 'int'&gt;, {'Adding an Entry!': 0})</span>
</code></pre>
<h2 id="heading-exploring-the-possibilities-of-defaultdict">Exploring the Possibilities of DefaultDict</h2>
<p>Now that you know the basic usage of <code>defaultdict</code>, we can explore the possibilities.</p>
<p>As I mentioned earlier, the <code>default_factory</code> is a function without arguments. This means we can use built-in data types as well as custom-defined functions – so, as long as they don’t take arguments.</p>
<p>Let’s go back to our Mississippi example. I want to know the actual index of where all the letter I’s are. I’m going to use a <code>defaultdict</code> with a list for the <code>default_factory</code> argument so we can track all the indices.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> defaultdict

my_word = <span class="hljs-string">"Mississippi"</span>

d1 = defaultdict(list)

<span class="hljs-keyword">for</span> index, letter <span class="hljs-keyword">in</span> enumerate(my_word):
    <span class="hljs-keyword">if</span> letter == <span class="hljs-string">"i"</span>:
        d1[letter].append(index)

print(d1)
<span class="hljs-comment"># defaultdict(&lt;class 'list'&gt;, {'i': [1, 4, 7, 10]})</span>
</code></pre>
<p>Awesome! I hand-checked this example, and it looks like it’s correct. There is the letter I located at index 1, 4, 7, and 10.</p>
<p>This example looks a little different, but the idea is still the same. Here are the steps:</p>
<ul>
<li>I created a <code>defaultdict</code> with the <code>default_factory</code> argument of <code>list</code>.</li>
<li>I iterated through the word “Mississippi”. </li>
<li>If the iterated letter equals “i”, I access the dictionary with the key “i”. </li>
<li>If that entry in the dictionary does not already exist, the <code>defaultdict</code> data container will create it for me and use an empty list as the value.</li>
<li>I then use the list’s append method to add the index of the iterated letter.</li>
</ul>
<p>Let’s explore some more. Since the <code>default_factory</code> takes a function as an argument, we can define our own – so as long as our custom function does not take an argument.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> defaultdict

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">return_hello</span>():</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello!"</span>

d1 = defaultdict(return_hello)

d1[<span class="hljs-number">1</span>]
d1[<span class="hljs-number">2</span>]
d1[<span class="hljs-number">3</span>]

print(d1)
<span class="hljs-comment"># defaultdict(&lt;function return_hello at 0x0000014FC5D28DC0&gt;, {1: 'Hello!', 2: 'Hello!', 3: 'Hello!'})</span>
</code></pre>
<p>I defined a function here to simply return “Hello!” and assigned it to the <code>default_factory</code> argument. Now, when we try to access entries in our dictionary that do not exist, the <code>defaultdict</code> calls my custom function to determine the default value!</p>
<h2 id="heading-to-recap">To Recap</h2>
<p>In this guide, we went over the <code>defaultdict</code>, which is a data container in the built-in collections module from the Python Standard Library. It allows us to access entries in a dictionary that do not exist by creating them on the fly and assigning a default value.</p>
<p>We saw that the <code>defaultdict</code> takes a <code>default_factory</code> argument, which tells the dictionary the default value to give a key. These can be built-in functions, such as <code>int</code> or <code>list</code>, or can be custom-defined functions, such as our <code>return_hello</code> function above.</p>
<p>I hope you learned something today!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Check if a Key Exists in a Dictionary in Python – Python Dict Has Key ]]>
                </title>
                <description>
                    <![CDATA[ Python is one of the most popular programming languages today. Its usage cuts across multiple fields, but the most common ones are data science, machine learning, and web development.  When you're coding in Python, you'll use different data structure... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-check-if-a-key-exists-in-a-dictionary-in-python/</link>
                <guid isPermaLink="false">66b8dbcd57c651c38343a9b6</guid>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Hillary Nyakundi ]]>
                </dc:creator>
                <pubDate>Tue, 27 Jun 2023 16:59:26 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/06/CoverImage-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Python is one of the most popular programming languages today. Its usage cuts across multiple fields, but the most common ones are data science, machine learning, and web development. </p>
<p>When you're coding in Python, you'll use different data structures. In Python, among the most used is the dictionary. </p>
<p>A dictionary is a collection of key-value pairs that allows you to store and retrieve data. </p>
<p>When working with dictionaries, it's a common practice to check if a key exists or not. This can be most helpful when you are working with a large dataset and need to access values based on their keys. </p>
<p>In this article, we are going to explore different ways that we can use to check if a key exists in a dictionary in Python. Let's get started.</p>
<h2 id="heading-method-1-using-the-in-operator">Method 1: Using the <code>in</code> Operator</h2>
<p>You can use the <code>in</code> operator to check if a key exists in a dictionary. It's one of the most straightforward ways of accomplishing the task. When used, it returns either a <code>True</code> if present and a <code>False</code> if otherwise. </p>
<p>You can see an example of how to use it below:</p>
<pre><code class="lang-python">my_dict = {<span class="hljs-string">'key1'</span>: <span class="hljs-string">'value1'</span>, <span class="hljs-string">'key2'</span>: <span class="hljs-string">'value2'</span>, <span class="hljs-string">'key3'</span>: <span class="hljs-string">'value3'</span>}

<span class="hljs-keyword">if</span> <span class="hljs-string">'key1'</span> <span class="hljs-keyword">in</span> my_dict:
    print(<span class="hljs-string">"Key exists in the dictionary."</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"Key does not exist in the dictionary."</span>)
</code></pre>
<p>From the code sample above, we check if <code>key1</code> exists in <code>my_dict</code>. If it does, then the confirmation message will be displayed. If not, the message indicating the key does not exist gets printed. </p>
<h2 id="heading-method-2-using-the-dictget-method">Method 2: Using the <code>dict.get()</code> Method</h2>
<p>The <code>dict.get()</code> method will return the value associated with a given key if it exists and <code>None</code> if the requested key is not found. </p>
<pre><code class="lang-python">my_dict = {<span class="hljs-string">'key1'</span>: <span class="hljs-string">'value1'</span>, <span class="hljs-string">'key2'</span>: <span class="hljs-string">'value2'</span>, <span class="hljs-string">'key3'</span>: <span class="hljs-string">'value3'</span>}

<span class="hljs-keyword">if</span> my_dict.get(<span class="hljs-string">'key1'</span>) <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
    print(<span class="hljs-string">"Key exists in the dictionary."</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"Key does not exist in the dictionary."</span>)
</code></pre>
<p>From the code sample above, we used the <code>dict.get()</code> method to get the values associated with <code>key1</code>. If the requested key is present, the <code>my_dict.get('key1') is not None</code> evaluates to True, meaning the requested key is present.</p>
<h2 id="heading-method-3-using-exception-handling">Method 3: Using Exception Handling</h2>
<p>Exception handling allows you to first try and access the value of the key and handle the <code>KeyError</code> exception if it occurs. </p>
<pre><code class="lang-python">my_dict = {<span class="hljs-string">'key1'</span>: <span class="hljs-string">'value1'</span>, <span class="hljs-string">'key2'</span>: <span class="hljs-string">'value2'</span>, <span class="hljs-string">'key3'</span>: <span class="hljs-string">'value3'</span>}

<span class="hljs-keyword">try</span>:
    value = my_dict[<span class="hljs-string">'key1'</span>]
    print(<span class="hljs-string">"Key exists in the dictionary."</span>)
<span class="hljs-keyword">except</span> KeyError:
    print(<span class="hljs-string">"Key does not exist in the dictionary."</span>)
</code></pre>
<p>The code sample above allows us to access the value associated with <code>key1</code>. If it exists, the code inside <code>try</code> executes and the message gets printed. But if the <code>KeyError</code> exception occurs, then it means the key does not exist and the code inside the <code>except</code> block will be executed. </p>
<h3 id="heading-additional-points">Additional Points</h3>
<ul>
<li><p><strong>Key exists versus value exists</strong>
The methods we have discussed above only check if a key exists. If we were to check if a value is present, we will need to iterate through the values using methods like <code>dictname.values()</code>.</p>
</li>
<li><p><strong>Performance considerations</strong>
Different methods may have different performance implications depending on the size of your dictionary. Generally the <code>in</code> operator is best for small to medium-sized dictionaries while <code>dict.get()</code> and exemption handling are a good fit for large dictionaries.</p>
</li>
<li><p><strong>Combining methods</strong>
A good thing about working with Python dictionary methods is that you can combine them. For example, you can use the <code>in</code> operator to check if a key exists and the <code>dict.get()</code> to retrieve its value if it exists.</p>
</li>
<li><p><strong>Using <code>dict.setdefault()</code></strong>
It allows you to check if a key exists and returns the value if present. In case the key is missing, then you can set a default value while adding it to the dictionary at the same time.</p>
</li>
</ul>
<p>With an understanding of the above points and good practice using these methods, you should be comfortable working with dictionaries in Python. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Sort Dictionary by Key – How to Sort a Dict with Keys ]]>
                </title>
                <description>
                    <![CDATA[ By Shittu Olumide Sorting is a fundamental operation in computer programming that involves arranging elements in a specific order. Whether you're working with numbers, strings, or complex data structures, sorting plays a crucial role in organizing an... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-sort-dictionary-by-key/</link>
                <guid isPermaLink="false">66d46138d1ffc3d3eb89de6e</guid>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 25 May 2023 23:57:54 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/Shittu-Olumide-Python-Sort-Dictionary-by-Key---How-to-Sort-a-Dict-with-Keys.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Shittu Olumide</p>
<p>Sorting is a fundamental operation in computer programming that involves arranging elements in a specific order.</p>
<p>Whether you're working with numbers, strings, or complex data structures, sorting plays a crucial role in organizing and manipulating data efficiently.</p>
<p>From small arrays to large datasets, sorting algorithms allow programmers to solve a wide range of problems, from searching for specific values to optimizing data access and analysis.</p>
<p>In this article, we will explore how to sort a dictionary with keys in Python. We will break down the steps for easy follow up and understanding. I recommend that you be familiar with the Python programming language to get the most out of this article.</p>
<h2 id="heading-what-is-a-python-dictionary">What is a Python Dictionary?</h2>
<p>In Python, dictionaries are a powerful data structure used to store key-value pairs. They provide a convenient way to organize and retrieve data based on unique keys. But there may be situations where you need to sort a dictionary by its keys in a specific order.</p>
<p>A key in Python refers to the unique identifier associated with a specific value. It serves as a way to access and retrieve values from the dictionary based on their corresponding keys. Keys in a dictionary can be of any immutable data type, such as strings, numbers (integers or floats), or tuples. The key must be unique within the dictionary, meaning that no two keys can have the same value.</p>
<h2 id="heading-ways-to-sort-a-dict-by-keys-in-python">Ways to Sort a Dict by Keys in Python</h2>
<h3 id="heading-method-1-using-the-sorted-function">Method 1: Using the <code>sorted()</code> Function</h3>
<p>The simplest way to sort a dictionary by its keys is by using the <code>sorted()</code> function along with the <code>items()</code> method of the dictionary. </p>
<p>The <code>items()</code> method returns a list of key-value pairs as tuples. By passing this list to the <code>sorted()</code> function, we can sort the tuples based on their first element (the keys). </p>
<p>Example:</p>
<pre><code class="lang-py">my_dict = {<span class="hljs-string">'b'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'a'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'c'</span>: <span class="hljs-number">3</span>}
sorted_dict = dict(sorted(my_dict.items()))

print(sorted_dict)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{<span class="hljs-string">'a'</span>: 1, <span class="hljs-string">'b'</span>: 2, <span class="hljs-string">'c'</span>: 3}
</code></pre>
<p>In this example, the <code>sorted()</code> function takes the <code>my_dict.items()</code> list and returns a new sorted list of tuples. We use the <code>dict()</code> constructor to convert the sorted list back into a dictionary.</p>
<h3 id="heading-method-2-using-a-list-of-tuples">Method 2: Using a List of Tuples</h3>
<p>If you prefer a more manual approach, you can convert the dictionary to a list of tuples, sort the list using any sorting technique available in Python, and then convert it back to a dictionary. </p>
<p>Example:</p>
<pre><code class="lang-py">my_dict = {<span class="hljs-string">'b'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'a'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'c'</span>: <span class="hljs-number">3</span>}
sorted_list = sorted(my_dict.items())

sorted_dict = {}
<span class="hljs-keyword">for</span> key, value <span class="hljs-keyword">in</span> sorted_list:
    sorted_dict[key] = value

print(sorted_dict)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{<span class="hljs-string">'a'</span>: 1, <span class="hljs-string">'b'</span>: 2, <span class="hljs-string">'c'</span>: 3}
</code></pre>
<p>In this example, we used the <code>sorted()</code> function to sort the <code>my_dict.items()</code> list. Then, a new empty dictionary, <code>sorted_dict</code>, is created. The sorted list is iterated over, and each key-value pair is added to the <code>sorted_dict</code> using assignment.</p>
<h3 id="heading-method-3-using-the-collectionsordereddict-class">Method 3: Using the <code>collections.OrderedDict</code> Class</h3>
<p>Another approach to sorting a dictionary by key is to use the <code>collections.OrderedDict</code> class from the Python standard library. </p>
<p>This class is a dict subclass that remembers the order of its elements based on the insertion order. We can leverage this feature to achieve key-based sorting. </p>
<p>Example:</p>
<pre><code class="lang-py"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> OrderedDict

my_dict = {<span class="hljs-string">'b'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'a'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'c'</span>: <span class="hljs-number">3</span>}
sorted_dict = OrderedDict(sorted(my_dict.items()))

print(sorted_dict)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">OrderedDict([(<span class="hljs-string">'a'</span>, 1), (<span class="hljs-string">'b'</span>, 2), (<span class="hljs-string">'c'</span>, 3)])
</code></pre>
<p>In this example, the <code>sorted()</code> function is used to sort the <code>my_dict.items()</code> list, and then the sorted list is passed to the <code>OrderedDict()</code> constructor to create a new dictionary with the sorted order.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In Python, you can sort a dictionary by its keys using various methods. In this article, we explored three approaches: using the <code>sorted()</code> function, utilizing the <code>collections.OrderedDict</code> class, and manually sorting a list of tuples. Each method provides a different level of control and flexibility.</p>
<p>By using the <code>sorted()</code> function, we can quickly sort a dictionary by key and obtain a new dictionary as the result. If preservation of the insertion order is crucial, the <code>collections.OrderedDict</code> class is a suitable choice.</p>
<p>For those who prefer a more manual approach, converting the dictionary to a list of tuples, sorting the list, and then creating a new dictionary can provide more customization options.</p>
<p>Let's connect on <a target="_blank" href="https://www.twitter.com/Shittu_Olumide_">Twitter</a> and on <a target="_blank" href="https://www.linkedin.com/in/olumide-shittu">LinkedIn</a>. You can also subscribe to my <a target="_blank" href="https://www.youtube.com/channel/UCNhFxpk6hGt5uMCKXq0Jl8A">YouTube</a> channel.</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Merge Dictionaries – Merging Two Dicts in Python ]]>
                </title>
                <description>
                    <![CDATA[ Dictionaries are one of the built-in data structures in Python. You can use them to store data in key-value pairs.  You can read about the different methods you can use to access, modify, add, and remove elements in a dictionary here.  In this articl... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-merge-dictionaries-merging-two-dicts-in-python/</link>
                <guid isPermaLink="false">66b0a34b3ac4671a1e5802fa</guid>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Thu, 11 May 2023 21:51:40 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/hannah-busing-Zyx1bK9mqmA-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Dictionaries are one of the built-in data structures in Python. You can use them to store data in key-value pairs. </p>
<p>You can read about the different methods you can use to access, modify, add, and remove elements in a dictionary <a target="_blank" href="https://www.freecodecamp.org/news/python-dictionary-methods-dictionaries-in-python/">here</a>. </p>
<p>In this article, you'll learn how to merge two dictionaries using the following:</p>
<ul>
<li>The <code>update()</code> method.</li>
<li>The double asterisk/star operator (<code>**</code>). </li>
<li>The <code>chain()</code> method.</li>
<li>The <code>ChainMap()</code> method.</li>
<li>The merge operator (<code>|</code>).</li>
<li>The update operator (<code>|=</code>).</li>
</ul>
<h2 id="heading-how-to-merge-two-dictionaries-in-python">How to Merge Two Dictionaries in Python</h2>
<p>In this section, we'll discuss the different methods you can use to merge dictionaries in Python, along with code examples.</p>
<p>All the examples you'll see in this article will involve the merging of two dictionaries, but you can merge as many as you want.</p>
<h3 id="heading-how-to-merge-two-dictionaries-in-python-using-the-update-method">How to Merge Two Dictionaries in Python Using the <code>update()</code> Method</h3>
<p>The <code>update()</code> method is a built-in method that you can use to add data to dictionaries. </p>
<p>Consider the dictionary below:</p>
<pre><code class="lang-python">devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">500</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"Python"</span>
}

devBio.update({<span class="hljs-string">"role"</span>: <span class="hljs-string">"Technical Writer"</span>})

print(devBio)
<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 500, 'language': 'Python', 'role': 'Technical Writer'}</span>
</code></pre>
<p>In the code above, we created a dictionary called <code>devBio</code> with three key and value pairs: <code>{'name': 'Ihechikara', 'age': 50, 'language': 'Python'}</code>. </p>
<p>Using the <code>update()</code> method, we added another key and value pair: <code>devBio.update({"role": "Technical Writer"})</code>. </p>
<p>In the same manner, we can merge two dictionaries by passing another dictionary as a parameter to the <code>update()</code> method. Here's an example:</p>
<pre><code class="lang-python">devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">500</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"Python"</span>
}

tools = {
  <span class="hljs-string">"dev environment"</span>: <span class="hljs-string">"JupyterLab"</span>,
  <span class="hljs-string">"os"</span>: <span class="hljs-string">"Windows"</span>,
  <span class="hljs-string">"visualization"</span>: <span class="hljs-string">"Matplotlib"</span>
}

devBio.update(tools)

print(devBio)
<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 500, 'language': 'Python', 'dev environment': 'JupyterLab', 'os': 'Windows', 'visualization': 'Matplotlib'}</span>
</code></pre>
<p>In the code above, we created two dictionaries — <code>devBio</code> and <code>tools</code>. </p>
<p>Using the <code>update()</code> method, we merged the key and value pairs of the <code>tools</code> dictionary to the <code>devBio</code> dictionary: <code>devBio.update(tools)</code>. </p>
<p>The merged dictionaries looked like this: </p>
<pre><code class="lang-python">{
    <span class="hljs-string">'name'</span>: <span class="hljs-string">'Ihechikara'</span>, 
    <span class="hljs-string">'age'</span>: <span class="hljs-number">500</span>, 
    <span class="hljs-string">'language'</span>: <span class="hljs-string">'Python'</span>, 
    <span class="hljs-string">'dev environment'</span>: <span class="hljs-string">'JupyterLab'</span>, 
    <span class="hljs-string">'os'</span>: <span class="hljs-string">'Windows'</span>, 
    <span class="hljs-string">'visualization'</span>: <span class="hljs-string">'Matplotlib'</span>
}
</code></pre>
<h3 id="heading-how-to-merge-two-dictionaries-in-python-using-the-double-asterisk-operator">How to Merge Two Dictionaries in Python Using the Double Asterisk Operator (<code>**</code>)</h3>
<p>You can use the double asterisk (also called double star) operator (<code>**</code>) to "unpack" and merge the key and value pairs of two or more dictionaries into a variable. </p>
<p>Here's a code example: </p>
<pre><code class="lang-python">devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">500</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"Python"</span>
}

tools = {
  <span class="hljs-string">"dev environment"</span>: <span class="hljs-string">"JupyterLab"</span>,
  <span class="hljs-string">"os"</span>: <span class="hljs-string">"Windows"</span>,
  <span class="hljs-string">"visualization"</span>: <span class="hljs-string">"Matplotlib"</span>
}

merged_bio = { **devBio, **tools}

print(merged_bio)
<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 500, 'language': 'Python', 'dev environment': 'JupyterLab', 'os': 'Windows', 'visualization': 'Matplotlib'}</span>
</code></pre>
<p>In the code above, we unpacked the <code>devBio</code> and <code>tools</code> dictionaries using the double asterisk operator: <code>{ **devBio, **tools}</code>. </p>
<p>We then stored them in a variable called <code>merged_bio</code>. </p>
<h3 id="heading-how-to-merge-two-dictionaries-in-python-using-the-chain-method">How to Merge Two Dictionaries in Python Using the <code>chain()</code> Method</h3>
<p>The <code>chain()</code> method takes multiple iterable objects as its parameter. It merges and returns the objects as one iterable object. </p>
<p>You have to import the <code>chain()</code> method from the <code>itertools</code> module before using it: </p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> itertools <span class="hljs-keyword">import</span> chain

devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">500</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"Python"</span>
}

tools = {
  <span class="hljs-string">"dev environment"</span>: <span class="hljs-string">"JupyterLab"</span>,
  <span class="hljs-string">"os"</span>: <span class="hljs-string">"Windows"</span>,
  <span class="hljs-string">"visualization"</span>: <span class="hljs-string">"Matplotlib"</span>
}

merged_bio = dict(chain(devBio.items(), tools.items()))

print(merged_bio)
<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 500, 'language': 'Python', 'dev environment': 'JupyterLab', 'os': 'Windows', 'visualization': 'Matplotlib'}</span>
</code></pre>
<p>In the code above, we passed the dictionaries to be merged as parameters to the <code>chain()</code> method: <code>chain(devBio.items(), tools.items())</code>. </p>
<p>We used the <code>items()</code> method to access the key and value pairs of each dictionary. </p>
<p>Lastly, we nested the <code>chain()</code> method and its parameters in the <code>dict()</code> method: <code>dict(chain(devBio.items(), tools.items()))</code>.</p>
<p>The <code>dict()</code> method can be used to create a dictionary so we used it to convert the iterable objects returned (the key and value pairs) into a dictionary, and stored them in the <code>merged_bio</code> variable.</p>
<h3 id="heading-how-to-merge-two-dictionaries-in-python-using-the-chainmap-method">How to Merge Two Dictionaries in Python Using the <code>ChainMap()</code> Method</h3>
<p>The <code>ChainMap()</code> method works the same way as the <code>chain()</code> method as regards to merging dictionaries. The main difference is that you don't need the <code>items()</code> method to access the key and value pairs of the dictionaries. </p>
<p>You can import the <code>ChainMap()</code> method from the <code>collections</code> module. </p>
<p>Here's how you can use the <code>ChainMap()</code> method to merger two dictionaries:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> ChainMap

devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">500</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"Python"</span>
}

tools = {
  <span class="hljs-string">"dev environment"</span>: <span class="hljs-string">"JupyterLab"</span>,
  <span class="hljs-string">"os"</span>: <span class="hljs-string">"Windows"</span>,
  <span class="hljs-string">"visualization"</span>: <span class="hljs-string">"Matplotlib"</span>
}

merged_bio = dict(ChainMap(devBio, tools))

print(merged_bio)
<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 500, 'language': 'Python', 'dev environment': 'JupyterLab', 'os': 'Windows', 'visualization': 'Matplotlib'}</span>
</code></pre>
<p>You can check the explanation in the last section to understand the logic in the code above. </p>
<h3 id="heading-how-to-merge-two-dictionaries-in-python-using-the-merge-operator">How to Merge Two Dictionaries in Python Using the Merge Operator (<code>|</code>)</h3>
<p>The merge operator (<code>|</code>) was first introduced in Python 3.9. It's a shorter and simpler syntax that you can use to merge dictionaries. </p>
<p>Here's an example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> ChainMap

devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">500</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"Python"</span>
}

tools = {
  <span class="hljs-string">"dev environment"</span>: <span class="hljs-string">"JupyterLab"</span>,
  <span class="hljs-string">"os"</span>: <span class="hljs-string">"Windows"</span>,
  <span class="hljs-string">"visualization"</span>: <span class="hljs-string">"Matplotlib"</span>
}

merged_bio = devBio | tools

print(merged_bio)
<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 500, 'language': 'Python', 'dev environment': 'JupyterLab', 'os': 'Windows', 'visualization': 'Matplotlib'}</span>
</code></pre>
<p>So to merge the <code>devBio</code> and <code>tools</code> dictionary, we put the <code>|</code> operator between them:  <code>devBio | tools</code>.</p>
<h3 id="heading-how-to-merge-two-dictionaries-in-python-using-the-update-operator">How to Merge Two Dictionaries in Python Using the Update Operator (<code>|=</code>)</h3>
<p>The update operator (<code>|=</code>) operator is another operator that was introduced in Python 3.9. </p>
<p>It works just like the <code>update()</code> method. That is: </p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> ChainMap

devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">500</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"Python"</span>
}

tools = {
  <span class="hljs-string">"dev environment"</span>: <span class="hljs-string">"JupyterLab"</span>,
  <span class="hljs-string">"os"</span>: <span class="hljs-string">"Windows"</span>,
  <span class="hljs-string">"visualization"</span>: <span class="hljs-string">"Matplotlib"</span>
}

devBio |= tools

print(devBio)
<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 50, 'language': 'Python', 'dev environment': 'JupyterLab', 'os': 'Windows', 'visualization': 'Matplotlib'}</span>
</code></pre>
<p>In the code above, we used the <code>|=</code> to mege the key and value pairs in the <code>tools</code> dictionary into the <code>devBio</code> dictionary.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about dictionaries in Python. You can use them to store data in key-value pairs. </p>
<p>We saw how to merge two dictionaries in Python using:</p>
<ul>
<li>The <code>update()</code> method.</li>
<li>The double asterisk/star operator (<code>**</code>). </li>
<li>The <code>chain()</code> method.</li>
<li>The <code>ChainMap()</code> method.</li>
<li>The merge operator (<code>|</code>).</li>
<li>The update operator (<code>|=</code>).</li>
</ul>
<p>Each method had its own section with code examples that showed how to use them to merge dictionaries. </p>
<p>Happy coding! You can learn more about Python on <a target="_blank" href="https://ihechikara.com/">my blog</a>. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Iterate Over Dictionary – How to Loop Through a Dict ]]>
                </title>
                <description>
                    <![CDATA[ By Shittu Olumide In this article, we will talk about dictionaries, and also learn how to loop through a dictionary in python. Python Dictionaries In Python, a dictionary is a built-in data structure used to store and organize data in key-value pairs... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-iterate-over-dictionary-how-to-loop-through-a-dict/</link>
                <guid isPermaLink="false">66d4612b182810487e0ce1b2</guid>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 10 Mar 2023 21:10:23 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/Shittu-Olumide-Python-Iterate-Over-Dictionary---How-to-Loop-Through-a-Dict-2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Shittu Olumide</p>
<p>In this article, we will talk about dictionaries, and also learn how to loop through a dictionary in python.</p>
<h2 id="heading-python-dictionaries">Python Dictionaries</h2>
<p>In Python, a dictionary is a built-in data structure used to store and organize data in key-value pairs. </p>
<p>A dictionary has two parts for each entry: a key and a value. The associated value can be accessed using the key, a special identifier. Any data type, including a number, string, list, or another dictionary, may be used as the value.</p>
<p>Dictionaries can be created by explicitly assigning values to keys or by using the <code>dict()</code> constructor function. They are indicated by curly braces <code>{ }</code>. Here is an illustration of a basic dictionary:</p>
<pre><code class="lang-py">DemoDict = {<span class="hljs-string">'name'</span>: <span class="hljs-string">'John'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">25</span>, <span class="hljs-string">'city'</span>: <span class="hljs-string">'New Jersey'</span>}
</code></pre>
<p>In this example, the keys are <code>'name'</code>, <code>'age'</code>, and <code>'city'</code>, and the corresponding values are <code>'John'</code>, <code>25</code>, and <code>'New Jersey'</code>, respectively.</p>
<p>We will now check out the different methods for looping through a dictionary: the <code>items()</code> method, the <code>keys()</code> method, the <code>values()</code> method, and using list comprehension.</p>
<h2 id="heading-how-to-iterate-through-a-dict-using-the-items-method">How to Iterate Through a Dict Using the <code>items()</code> Method</h2>
<p>We can use the <code>items()</code> method to loop through a dictionary and get both the key and value pairs.</p>
<p>Let's consider an example:</p>
<pre><code class="lang-py">DemoDict = {<span class="hljs-string">'apple'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'banana'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'orange'</span>: <span class="hljs-number">3</span>}

<span class="hljs-comment"># Loop through the dictionary</span>
<span class="hljs-keyword">for</span> key, value <span class="hljs-keyword">in</span> my_dict.items():
    print(key, value)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">apple 1
banana 2
orange 3
</code></pre>
<h2 id="heading-how-to-iterate-through-a-dict-using-the-keys-method">How to Iterate Through a Dict Using the <code>keys()</code> Method</h2>
<p>If we only want to loop through the keys of the dictionary, we can use the <code>keys()</code> method.</p>
<pre><code class="lang-py">DemoDict = {<span class="hljs-string">'apple'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'banana'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'orange'</span>: <span class="hljs-number">3</span>}

<span class="hljs-comment"># Loop through the keys of the dictionary</span>
<span class="hljs-keyword">for</span> key <span class="hljs-keyword">in</span> my_dict.keys():
    print(key)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">apple
banana
orange
</code></pre>
<h2 id="heading-how-to-iterate-through-a-dict-using-the-values-method">How to Iterate Through a Dict Using the <code>values()</code> Method</h2>
<p>Similarly, if we only want to loop through the values of the dictionary, we can use the <code>values()</code> method.</p>
<pre><code class="lang-py">my_dict = {<span class="hljs-string">'apple'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'banana'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'orange'</span>: <span class="hljs-number">3</span>}

<span class="hljs-comment"># Loop through the values of the dictionary</span>
<span class="hljs-keyword">for</span> value <span class="hljs-keyword">in</span> my_dict.values():
    print(value)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">1
2
3
</code></pre>
<h2 id="heading-how-to-iterate-through-a-dict-using-list-comprehension">How to Iterate Through a Dict Using List Comprehension</h2>
<p>Finally, we can also use list comprehension to loop through a dictionary and get both the key and value pairs.</p>
<p>Let's demonstrate this with an example:</p>
<pre><code class="lang-py">my_dict = {<span class="hljs-string">'apple'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'banana'</span>: <span class="hljs-number">3</span>, <span class="hljs-string">'orange'</span>: <span class="hljs-number">4</span>}

<span class="hljs-comment"># Loop through the dictionary using list comprehension</span>
[(key, value) <span class="hljs-keyword">for</span> key, value <span class="hljs-keyword">in</span> my_dict.items()]
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">[(<span class="hljs-string">'apple'</span>, 1), (<span class="hljs-string">'banana'</span>, 2), (<span class="hljs-string">'orange'</span>, 3)]
</code></pre>
<p><strong>Note</strong>: The output of list comprehension is a list of tuples where each tuple contains a key-value pair of the dictionary.</p>
<h2 id="heading-key-differences-between-methods-of-looping-through-a-dictionary-in-python">Key Differences Between Methods of Looping Through a Dictionary in Python</h2>
<h3 id="heading-compatibility-with-different-python-versions">Compatibility with different Python versions:</h3>
<ul>
<li>The <code>items()</code> method and <code>values()</code> method were introduced in Python 3, so they are not compatible with Python 2. If you need to write code that is compatible with both Python 2 and 3, you should use a basic for loop to iterate through the keys of the dictionary.</li>
<li>The <code>keys()</code> method is compatible with both Python 2 and 3, so it is a good option if you need to write code that works on both versions of Python.</li>
</ul>
<h3 id="heading-performance">Performance:</h3>
<ul>
<li>In general, using a basic for loop to iterate through the keys of a dictionary is the fastest method of looping through a dictionary in Python. This is because it avoids the overhead of creating a list of the dictionary's keys or items.</li>
<li>The <code>items()</code> method is slower than a basic for loop because it creates a new list of tuples that contains the key-value pairs of the dictionary.</li>
<li>The <code>values()</code> method is also slower than a basic for loop because it creates a new list of the values of the dictionary.</li>
</ul>
<h3 id="heading-access-to-keys-values-or-both">Access to keys, values, or both:</h3>
<ul>
<li>When using a basic for loop to iterate through a dictionary, you only have access to the keys of the dictionary. To access the corresponding values, you need to use the keys as the index to the dictionary.</li>
<li>The <code>items()</code> method provides a way to access both the keys and values of the dictionary in a single loop. This is convenient when you need to work with both the keys and values of a dictionary.</li>
<li>The <code>values()</code> method, on the other hand, allows you to access only the values of the dictionary. This can be useful when you don't need the keys but just want to work with the values themselves.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Dictionaries are incredibly useful for storing and retrieving data in a flexible and efficient manner. They are commonly used in Python programming for tasks such as data analysis, web development, and machine learning.</p>
<p>Let's connect on <a target="_blank" href="https://www.twitter.com/Shittu_Olumide_">Twitter</a> and on <a target="_blank" href="https://www.linkedin.com/in/olumide-shittu">LinkedIn</a>. You can also subscribe to my <a target="_blank" href="https://www.youtube.com/channel/UCNhFxpk6hGt5uMCKXq0Jl8A">YouTube</a> channel.</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Dictionary – How to Create a Dict in Python (Hashmap) ]]>
                </title>
                <description>
                    <![CDATA[ By Shittu Olumide Welcome to this Python article on how to create a dictionary. A dictionary (also called a hashmap in other languages) is an unordered grouping of key-value pairs in Python. Since each value can be accessed by its corresponding key, ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-dictionary-how-to-create-a-dict-in-python/</link>
                <guid isPermaLink="false">66d46124230dff0166905875</guid>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 01 Mar 2023 15:44:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/Shittu-Olumide-Python-Dictionary---How-to-Create-a-Dict-in-Python--Hashmap--1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Shittu Olumide</p>
<p>Welcome to this Python article on how to create a dictionary.</p>
<p>A dictionary (also called a hashmap in other languages) is an unordered grouping of key-value pairs in Python. Since each value can be accessed by its corresponding key, it offers a practical means of storing and retrieving data.</p>
<p>We'll cover the fundamentals of creating a dictionary in Python in this tutorial, including how to initialize an empty dictionary, how to add and remove key-value pairs, and how to access and work with dictionary data. </p>
<p>I'll illustrate each concept with examples, and demonstrate each operation with code snippets.</p>
<p>By the time you finish reading this article, you ought to know everything you need to use dictionaries in Python, from creating them to modifying them. And and you should be able to use this information to solve issues and construct more sophisticated programs. </p>
<p>Let's begin!</p>
<h2 id="heading-how-to-create-a-dict-in-python">How to Create a Dict in Python</h2>
<p>A dictionary is a type of data structure that allows us to store key-value pairs. It is also known as a hashmap in other programming languages. </p>
<p>Dictionaries are useful when we want to store data in a way that is easily accessible and modifiable. To create dictionaries in Python, we use curly braces, the <code>dict()</code> constructor, and the <code>fromkeys()</code> method.</p>
<h3 id="heading-how-to-create-a-dict-using-curly-braces">How to create a dict using curly braces</h3>
<p>Curly braces <code>{ }</code> are one method of creating a dictionary in Python. We can enclose a comma-separated list of key-value pairs in curly braces to make a dictionary. We use a colon and a comma to separate each pair of key-value pairs from the others.</p>
<p>Here's an example:</p>
<pre><code class="lang-py">MyDict = {<span class="hljs-number">1</span>: <span class="hljs-string">"apple"</span>, <span class="hljs-number">2</span>: <span class="hljs-string">"banana"</span>, <span class="hljs-number">3</span>: <span class="hljs-string">"orange"</span>}
</code></pre>
<p>In this example, we've created a dictionary <code>MyDict</code> with three key-value pairs:<br><code>1: "apple"</code>, <code>2: "banana"</code>, and <code>3: "orange"</code>. The keys are integers and the values are strings.</p>
<h3 id="heading-how-to-create-a-dict-using-the-dict-constructor">How to create a dict using the <code>dict()</code> constructor</h3>
<p>Another method for making a dictionary in Python is using the <code>dict()</code> constructor. The constructor <code>dict()</code> produces a dictionary from an iterable of key-value pairs as input. Both a list of tuples and arguments can be used to pass in the key-value pairs. As an illustration, consider the following.</p>
<p>Let's create a dictionary from a tuple.</p>
<pre><code class="lang-py"><span class="hljs-comment"># create a dictionary from a tuple using dict() constructor</span>
MyDict = dict(one=<span class="hljs-number">1</span>, two=<span class="hljs-number">2</span>, three=<span class="hljs-number">3</span>)
print(MyDict)
</code></pre>
<p>Output:</p>
<pre><code class="lang-py">{<span class="hljs-string">'one'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'two'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'three'</span>: <span class="hljs-number">3</span>}
</code></pre>
<p>Let's create a dictionary from a list of tuples.</p>
<pre><code class="lang-py"><span class="hljs-comment"># create a dictionary from a list of tuples using dict() constructor</span>
MyList = [(<span class="hljs-string">'one'</span>, <span class="hljs-number">1</span>), (<span class="hljs-string">'two'</span>, <span class="hljs-number">2</span>), (<span class="hljs-string">'three'</span>, <span class="hljs-number">3</span>)]
MyDict = dict(MyDict)
print(MyDict)
</code></pre>
<p>Output:</p>
<pre><code class="lang-py">{<span class="hljs-string">'one'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'two'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'three'</span>: <span class="hljs-number">3</span>}
</code></pre>
<p>In the first example, we created a dictionary with key-value pairs <code>one:1</code>, <code>two:2</code>, and <code>three:3</code> by passing them as arguments to the <code>dict()</code> constructor. </p>
<p>In the second example, we created a dictionary using a list of tuples <code>MyList</code>, which contains the same key-value pairs as before. We passed <code>MyList</code> as an argument to the <code>dict()</code> constructor, which returns a dictionary with the same key-value pairs.</p>
<p>The <code>dict()</code> constructor can also be used to create an empty dictionary by not passing any arguments. For example, <code>MyDict = dict()</code> creates an empty dictionary <code>MyDict</code>.</p>
<h3 id="heading-how-to-create-a-dict-using-the-fromkeys-method">How to create a dict using the <code>fromkeys()</code> method</h3>
<p>You can also use the built-in <code>fromkeys()</code> method to create a dictionary by selecting keys from a sequence and setting values to default values.</p>
<p>The first argument to the <code>fromkeys()</code> method is a list of keys, and the second (optional) argument is the value that will be assigned to each key after it has been set. The values will automatically be set to None if the second argument is not provided.</p>
<p>Example</p>
<pre><code class="lang-py">keys = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>]
values = <span class="hljs-number">0</span>  <span class="hljs-comment"># set default value to 0</span>

MyDict = dict.fromkeys(keys, values)
print(MyDict)
</code></pre>
<p>Output:</p>
<pre><code class="lang-py">{<span class="hljs-string">'a'</span>: <span class="hljs-number">0</span>, <span class="hljs-string">'b'</span>: <span class="hljs-number">0</span>, <span class="hljs-string">'c'</span>: <span class="hljs-number">0</span>}
</code></pre>
<p>In the example above, we passed a list of keys <code>['a', 'b', 'c']</code> and a default value <code>0</code> to the <code>fromkeys()</code> method. We get a new dictionary where all keys are set the value of <code>0</code>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, we learned how to create a dict in Python by focusing on three ways: using curly braces, the <code>dict()</code> constructor, and the <code>fromkeys()</code> method. With this knowledge, you can confidently create and manipulate dictionaries in your Python code.</p>
<p>Let's connect on <a target="_blank" href="https://www.twitter.com/Shittu_Olumide_">Twitter</a> and on <a target="_blank" href="https://www.linkedin.com/in/olumide-shittu">LinkedIn</a>. You can also subscribe to my <a target="_blank" href="https://www.youtube.com/channel/UCNhFxpk6hGt5uMCKXq0Jl8A">YouTube</a> channel.</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Adding to Dict in Python – How to Append to a Dictionary ]]>
                </title>
                <description>
                    <![CDATA[ By Shittu Olumide A dictionary in Python is a group of unordered items, each of which has a unique set of keys and values.  Any immutable data type, such as a string, number, or tuple, can be used as the key. It serves as an exclusive identifier for ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/add-to-dict-in-python/</link>
                <guid isPermaLink="false">66d460ee677cb8c6c15f3179</guid>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 28 Feb 2023 00:17:11 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/Shittu-Olumide-Adding-to-Dict-in-Python---How-to-Append-to-a-Dictionary-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Shittu Olumide</p>
<p>A dictionary in Python is a group of unordered items, each of which has a unique set of keys and values. </p>
<p>Any immutable data type, such as a string, number, or tuple, can be used as the key. It serves as an exclusive identifier for the value in the dictionary. The value is repeatable and applicable to all types of data.</p>
<p>In Python, dictionaries are denoted by curly braces <code>{ }</code>, and each key-value pair is delimited by a colon <code>:</code>. A comma separates the key and value. Here is an illustration of a basic dictionary:</p>
<pre><code class="lang-py">my_dict = {<span class="hljs-string">"pineapple"</span>: <span class="hljs-number">12</span>, <span class="hljs-string">"apple"</span>: <span class="hljs-number">30</span>, <span class="hljs-string">"orange"</span>: <span class="hljs-number">5</span>, <span class="hljs-string">"avocado"</span>:<span class="hljs-number">7</span>}
</code></pre>
<p>In this example, "pineapple", "apple", "orange", and "avocado" are the keys, and 12, 30, 5 and 7 are the corresponding values.</p>
<p>We will have a look at how we can add a single key-value pair to a dictionary using the <code>update()</code> method, and finally the  <code>dict()</code> constructor.</p>
<h3 id="heading-how-to-add-a-single-key-value-pair-to-a-dictionary">How to add a single key-value pair to a dictionary</h3>
<p>To add a single key-value pair to a dictionary in Python, we can use the following code:</p>
<pre><code class="lang-py">myDict = {<span class="hljs-string">'a'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'b'</span>: <span class="hljs-number">2</span>}
myDict[<span class="hljs-string">'c'</span>] = <span class="hljs-number">3</span>
</code></pre>
<p>The above code will create a dictionary <code>myDict</code> with two key-value pairs. Then we added a new key-value pair <code>'c' : 3</code> to the dictionary by just assigning the value <code>3</code> to the key <code>'c'</code>.  After the  code is executed, the dictionary <code>myDict</code> will now contain the key-value pair <code>'c': 3</code>.</p>
<p>Let's confirm this by printing the dictionary.</p>
<pre><code class="lang-py">print(myDict)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{<span class="hljs-string">'a'</span>: 1, <span class="hljs-string">'b'</span>: 2, <span class="hljs-string">'c'</span>: 3}
</code></pre>
<p>If there is a key <code>'c'</code> in the dictionary already, the value would be updated to 3.</p>
<h3 id="heading-how-to-add-multiple-key-value-pairs-with-the-update-method">How to add multiple key-value pairs with the <code>update()</code> method</h3>
<p>Multiple key-value pairs can be simultaneously added to a dictionary using the <code>update()</code> method. This method inserts new entries into the original dictionary from another dictionary or an iterable of key-value pairs as input. The value of an existing key in the original dictionary will be updated with the new value.</p>
<p>Example using the <code>update()</code> method to add multiple entries to a dictionary:</p>
<pre><code class="lang-py">myDict = {<span class="hljs-string">'a'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'b'</span>: <span class="hljs-number">2</span>}
new_data = {<span class="hljs-string">'c'</span>: <span class="hljs-number">3</span>, <span class="hljs-string">'d'</span>: <span class="hljs-number">4</span>}

myDict.update(new_data)

print(myDict)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{<span class="hljs-string">'a'</span>: 1, <span class="hljs-string">'b'</span>: 2, <span class="hljs-string">'c'</span>: 3, <span class="hljs-string">'d'</span>: 4}
</code></pre>
<p>Another fun thing about this method is that, we can use the <code>update()</code> method with an iterable of key-value pairs, such as a list of tuples. Let's see this in action.</p>
<pre><code class="lang-py">myDict = {<span class="hljs-string">'a'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'b'</span>: <span class="hljs-number">2</span>}
new_data = [(<span class="hljs-string">'c'</span>, <span class="hljs-number">3</span>), (<span class="hljs-string">'d'</span>, <span class="hljs-number">4</span>)]

myDict.update(new_data)

print(myDict)
</code></pre>
<p>The output is the same as the previous example:</p>
<pre><code class="lang-bash">{<span class="hljs-string">'a'</span>: 1, <span class="hljs-string">'b'</span>: 2, <span class="hljs-string">'c'</span>: 3, <span class="hljs-string">'d'</span>: 4}
</code></pre>
<h3 id="heading-how-to-update-a-dictionary-using-the-dict-constructor">How to update a dictionary using the <code>dict()</code> constructor</h3>
<p>In Python, a dictionary can be updated or made from scratch using the <code>dict()</code> constructor. By passing a dictionary containing the new key-value pair as an argument to the <code>dict()</code> constructor, we can add a single key-value pair to an existing dictionary.</p>
<p>Example:</p>
<pre><code class="lang-py">myDict = {<span class="hljs-string">'a'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'b'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'c'</span>: <span class="hljs-number">3</span>}
newDict = dict(myDict, d=<span class="hljs-number">4</span>)

print(newDict)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{<span class="hljs-string">'a'</span>: 1, <span class="hljs-string">'b'</span>: 2, <span class="hljs-string">'c'</span>: 3, <span class="hljs-string">'d'</span>: 4}
</code></pre>
<p>In this example, three key-value pairs were added to a brand-new dictionary called <code>myDict</code>. Then, we created a new dictionary called <code>newDict</code> using the <code>dict()</code> constructor, which also added the key-value pair <code>'d': 4'</code>. </p>
<p>When the two dictionaries are combined by the <code>dict()</code> constructor, any keys that are present in both dictionaries have their values overwritten by the value from the second dictionary (in this case, <code>'d': 4'</code>).</p>
<p>Keep in mind that a new dictionary can also be created using the <code>dict()</code> constructor from a list of key-value pairs, where each pair is represented by a tuple.</p>
<pre><code class="lang-py">MyList = [(<span class="hljs-string">'a'</span>, <span class="hljs-number">1</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-number">2</span>), (<span class="hljs-string">'c'</span>, <span class="hljs-number">3</span>)]
MyDict = dict(MyList)

print(MyDict)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{<span class="hljs-string">'a'</span>: 1, <span class="hljs-string">'b'</span>: 2, <span class="hljs-string">'c'</span>: 3}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In Python, dictionaries are frequently used to store data and provide quick access to it using a distinct key value. They come in handy when working with lists or tuples, where we need to access data using a specific identifier rather than its place in a sequence.</p>
<p>Let's connect on <a target="_blank" href="https://www.twitter.com/Shittu_Olumide_">Twitter</a> and on <a target="_blank" href="https://www.linkedin.com/in/olumide-shittu">LinkedIn</a>. You can also subscribe to my <a target="_blank" href="https://www.youtube.com/channel/UCNhFxpk6hGt5uMCKXq0Jl8A">YouTube</a> channel.</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Remove Key from Dictionary – How to Delete Keys from a Dict ]]>
                </title>
                <description>
                    <![CDATA[ By Shittu Olumide Dictionaries are a useful data type in Python for storing data in a key-value format. And there are times when you might need to remove a particular key-value pair from a dictionary.  You'll learn some dictionary basics, as well as ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-remove-key-from-dictionary/</link>
                <guid isPermaLink="false">66d461363bc3ab877dae2240</guid>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 22 Feb 2023 15:36:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/Python-Remove-Key-from-Dictionary---How-to-Delete-Keys-from-a-Dict-by-Shittu-Olumide-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Shittu Olumide</p>
<p>Dictionaries are a useful data type in Python for storing data in a key-value format. And there are times when you might need to remove a particular key-value pair from a dictionary. </p>
<p>You'll learn some dictionary basics, as well as how to delete keys, in this tutorial.</p>
<h2 id="heading-how-to-write-a-dict-in-python">How to Write a Dict in Python</h2>
<p>Dictionaries are denoted by curly braces <code>{}</code> and the key-value pairs are separated by colons <code>:</code>. For example, the following code initializes a dictionary with three key-value pairs:</p>
<pre><code class="lang-py">my_dict = {<span class="hljs-string">'apple'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'banana'</span>: <span class="hljs-number">3</span>, <span class="hljs-string">'orange'</span>: <span class="hljs-number">5</span>}
</code></pre>
<p>You can also initialize dictionaries using the built-in <code>dict()</code> function. For example:</p>
<pre><code class="lang-py">my_dict = dict(apple=<span class="hljs-number">2</span>, banana=<span class="hljs-number">3</span>, orange=<span class="hljs-number">5</span>)
</code></pre>
<p>Now I'll teach you how to securely remove keys from a Python dictionary. When I say "securely," I mean that if the key doesn't actually exist in the dictionary, the code won't throw an error. </p>
<p>We'll discover how to accomplish this using the <code>del</code> keyword, the <code>pop()</code> method, and the <code>popitem()</code> method. Finally, you'll see how to use Python to remove multiple keys from a dictionary.</p>
<p>Let's get started!</p>
<h2 id="heading-how-to-remove-a-key-from-a-dict-using-the-del-keyword">How to Remove a Key from a Dict Using the <code>del</code> Keyword</h2>
<p>The most popular method for removing a key:value pair from a dictionary is to use the <code>del</code> keyword. You can also use it to eliminate a whole dictionary or specific words. </p>
<p>Simply use the syntax shown below to access the value you need to delete:</p>
<pre><code class="lang-py"><span class="hljs-keyword">del</span> dictionary[key]
</code></pre>
<p>Let's have a look at an example:</p>
<pre><code class="lang-py">Members = {<span class="hljs-string">"John"</span>: <span class="hljs-string">"Male"</span>, <span class="hljs-string">"Kat"</span>: <span class="hljs-string">"Female"</span>, <span class="hljs-string">"Doe"</span>: <span class="hljs-string">"Female"</span> <span class="hljs-string">"Clinton"</span>: <span class="hljs-string">"Male"</span>}

<span class="hljs-keyword">del</span> Members[<span class="hljs-string">"Doe"</span>]
print(Members)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{<span class="hljs-string">"John"</span>: <span class="hljs-string">"Male"</span>, <span class="hljs-string">"Kat"</span>: <span class="hljs-string">"Female"</span>, <span class="hljs-string">"Clinton"</span>: <span class="hljs-string">"Male"</span>}
</code></pre>
<h2 id="heading-how-to-remove-a-key-from-a-dict-using-the-pop-method">How to Remove a Key from a Dict Using the <code>pop()</code> Method</h2>
<p>Another technique to remove a key-value pair from a dictionary is to use the <code>pop()</code> method. The syntax is shown below:</p>
<pre><code class="lang-py">dictionary.pop(key, default_value)
</code></pre>
<p>Example:</p>
<pre><code class="lang-py">My_Dict = {<span class="hljs-number">1</span>: <span class="hljs-string">"Mathew"</span>, <span class="hljs-number">2</span>: <span class="hljs-string">"Joe"</span>, <span class="hljs-number">3</span>: <span class="hljs-string">"Lizzy"</span>, <span class="hljs-number">4</span>: <span class="hljs-string">"Amos"</span>}
data = My_Dict.pop(<span class="hljs-number">1</span>)
print(data)
print(My_Dict)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">Mathew
{2: <span class="hljs-string">"Joe"</span>, 3: <span class="hljs-string">"Lizzy"</span>, 4: <span class="hljs-string">"Amos"</span>}
</code></pre>
<h2 id="heading-how-to-remove-a-key-from-a-dict-using-the-popitem-function">How to Remove a Key from a Dict Using the <code>popitem()</code> Function</h2>
<p>The built-in <code>popitem()</code> function eliminates the the last key:value pair from a dictionary. The element that needs to be removed cannot be specified and the function doesn't accept any inputs.</p>
<p>The syntax looks like this:</p>
<pre><code class="lang-py">dict.popitem()
</code></pre>
<p>Let's consider and example for a better understanding.</p>
<pre><code class="lang-py"><span class="hljs-comment"># initialize a dictionary</span>
My_dict = {<span class="hljs-number">1</span>: <span class="hljs-string">"Red"</span>, <span class="hljs-number">2</span>: <span class="hljs-string">"Blue"</span>, <span class="hljs-number">3</span>: <span class="hljs-string">"Green"</span>, <span class="hljs-number">4</span>: <span class="hljs-string">"Yello"</span>, <span class="hljs-number">5</span>: <span class="hljs-string">"Black"</span>}

<span class="hljs-comment"># using popitem()</span>
Deleted_key = My_dict.popitem()
print(Deleted_key)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">(5, <span class="hljs-string">'Black'</span>)
</code></pre>
<p>As you can see, the function removed the last key:value pair – <code>5: "Black"</code> – from the dictionary.</p>
<h2 id="heading-how-to-remove-multiple-keys-from-a-dict">How to Remove Multiple Keys from a Dict</h2>
<p>You can easily delete multiple keys from a dictionary using Python. The <code>.pop()</code> method, used in a loop over a list of keys, is the safest approach for doing this.</p>
<p>Let's examine how we can supply a list of unique keys to remove, including some that aren't present:</p>
<pre><code class="lang-py">My_dict = {<span class="hljs-string">'Sam'</span>: <span class="hljs-number">16</span>, <span class="hljs-string">'John'</span>: <span class="hljs-number">19</span>, <span class="hljs-string">'Alex'</span>: <span class="hljs-number">17</span>, <span class="hljs-string">'Doe'</span>: <span class="hljs-number">15</span>}

<span class="hljs-comment">#define the keys to remove</span>
keys = [<span class="hljs-string">'Sam'</span>, <span class="hljs-string">'John'</span>, <span class="hljs-string">'Doe'</span>]

<span class="hljs-keyword">for</span> key <span class="hljs-keyword">in</span> keys:
    My_dict.pop(key, <span class="hljs-literal">None</span>)

print(My_dict)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{<span class="hljs-string">'Alex'</span>: 17}
</code></pre>
<p>One thing to note is that in the <code>pop()</code> method inside the loop, we pass in <code>None</code> and the default value, just to make sure no <code>KeyError</code> is printed if a key doesn't exist.</p>
<h2 id="heading-how-to-remove-all-keys-from-a-dict-using-the-clear-method">How to Remove All Keys from a Dict Using the <code>clear()</code> Method</h2>
<p>You can use the <code>clear()</code> method to remove all key-value pairs from a dictionary. The syntax is as follows:</p>
<pre><code class="lang-py">dictionary.clear()
</code></pre>
<p>Example:</p>
<pre><code class="lang-py">Colors = {<span class="hljs-number">1</span>: <span class="hljs-string">"Red"</span>, <span class="hljs-number">2</span>: <span class="hljs-string">"Blue"</span>, <span class="hljs-number">3</span>: <span class="hljs-string">"Green"</span>}
Colors.clear()
print(Colors)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>For removing a key-value pair or several key-value pairs from a dictionary, we discussed a variety of Python methods in this article. </p>
<p>You can do so using the <code>del</code> keyword, which is the most common method of removing a key-value pair from a dictionary. The <code>pop()</code> method is useful when we need to remove a key-value pair and also get the value of the key-value pair. Using the <code>popitem()</code> function, we can remove the final key-value pair in a dictionary. </p>
<p>Also, if you need to remove all key:value pairs in a dictionary, you can use the <code>clear()</code> method.</p>
<p>Let's connect on <a target="_blank" href="https://www.twitter.com/Shittu_Olumide_">Twitter</a> and on <a target="_blank" href="https://www.linkedin.com/in/olumide-shittu">LinkedIn</a>. You can also subscribe to my <a target="_blank" href="https://www.youtube.com/channel/UCNhFxpk6hGt5uMCKXq0Jl8A">YouTube</a> channel.</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Adding to a Dict in Python – How to Add to a Dictionary ]]>
                </title>
                <description>
                    <![CDATA[ A Python dictionary is like a JavaScript object – it’s a sequence of key:value pairs. So, you can create them like this: stack_dict = {     "frontend": "JavaScript",     "backend": "Node JS",     "markup": "HTML and JSX", } To access the ]]>
                </description>
                <link>https://www.freecodecamp.org/news/adding-to-a-dict-in-python-how-to-add-to-a-dictionary/</link>
                <guid isPermaLink="false">66adf0676778e7bd69427be8</guid>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Thu, 22 Dec 2022 18:04:49 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/12/addToDict.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A Python dictionary is like a JavaScript object – it’s a sequence of <code>key:value</code> pairs. So, you can create them like this:</p>
<pre><code class="lang-py">stack_dict = {
    <span class="hljs-string">"frontend"</span>: <span class="hljs-string">"JavaScript"</span>,
    <span class="hljs-string">"backend"</span>: <span class="hljs-string">"Node JS"</span>,
    <span class="hljs-string">"markup"</span>: <span class="hljs-string">"HTML and JSX"</span>,
}
</code></pre>
<p>To access the value in the dictionary, you can do it this way: <code>dict[key]</code>. For example, if I want to access what the <code>frontend</code> key holds, I can do it like this:</p>
<pre><code class="lang-py">print(stack_dict[<span class="hljs-string">"frontend"</span>])
<span class="hljs-comment"># JavaScript</span>
</code></pre>
<p>But what if you want to add another entry to the dictionary without going back to the dictionary to put it there? That's what we are going to look at in this article. And I'm going to show you how to do it in 3 different ways.</p>
<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><a class="post-section-overview" href="#heading-how-to-add-to-a-dictionary-in-python">How to Add to a Dictionary in Python</a></li>
<li><a class="post-section-overview" href="#howtoaddtoadictionarybymappingakeytothedictionary">How to Add to a Dictionary by Mapping a key to the Dictionary</a></li>
<li><a class="post-section-overview" href="#howtoaddtoadictionarybyusingtheupdatemethod">How to Add to a Dictionary by Using the <code>update()</code> Method</a></li>
<li><a class="post-section-overview" href="#howtoaddtoadictionarybyusingtheifstatement">How to Add to a Dictionary by Using the <code>if</code> Statement</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-how-to-add-to-a-dictionary-in-python">How to Add to a Dictionary in Python</h2>
<p>You can add to a dictionary in three different ways:</p>
<ul>
<li>map a key to the dictionary </li>
<li>use the <code>update()</code> method</li>
<li>use an if statement</li>
</ul>
<h3 id="heading-how-to-add-to-a-dictionary-in-python-by-mapping-a-key-to-the-dictionary">How to Add to a Dictionary in Python by Mapping a key to the Dictionary</h3>
<p>If you want to add to a dictionary with this method, you'll need to add the value with the assignment operator.</p>
<pre><code class="lang-py">dict[<span class="hljs-string">"key"</span>] = <span class="hljs-string">"value"</span>`
</code></pre>
<p>This would also override the value of an existing key.</p>
<p>In the stack dictionary I defined earlier, there's no styling there:</p>
<pre><code class="lang-py">stack_dict = {
    <span class="hljs-string">"frontend"</span>: <span class="hljs-string">"JavaScript"</span>,
    <span class="hljs-string">"backend"</span>: <span class="hljs-string">"Node JS"</span>,
    <span class="hljs-string">"markup"</span>: <span class="hljs-string">"HTML and JSX"</span>,
}
</code></pre>
<p>So let's add a <code>styling</code> key and <code>CSS</code> value to the dictionary by mapping a new key to the dictionary:</p>
<pre><code class="lang-py">stack_dict[<span class="hljs-string">"styling"</span>] = <span class="hljs-string">"CSS"</span>

print(stack_dict)
<span class="hljs-comment"># Output: {'frontend': 'JavaScript', 'backend': 'Node JS', 'markup': 'HTML and JSX', 'styling': 'CSS'}</span>
</code></pre>
<p>You can see that a new key of <code>styling</code> and a value of <code>CSS</code> has been added to the dictionary.</p>
<p>If the key already exists, the value gets overwritten:</p>
<pre><code class="lang-py">stack_dict[<span class="hljs-string">"markup"</span>] = <span class="hljs-string">"HTML only"</span>
print(stack_dict)

<span class="hljs-comment"># {'frontend': 'JavaScript', 'backend': 'Node JS', 'markup': 'HTML only'}</span>
</code></pre>
<h3 id="heading-how-to-add-to-a-dictionary-in-python-using-the-update-method">How to Add to a Dictionary in Python Using the <code>update()</code> Method</h3>
<p>The stack is still missing a JavaScript library, so let's add it with the <code>update()</code> method. You can do that this way:</p>
<pre><code class="lang-py">dict.update({<span class="hljs-string">"key"</span>: <span class="hljs-string">"value"</span>})`.
</code></pre>
<p>So, to add the JavaScript framework/library, I did it like this:</p>
<pre><code class="lang-py">stack_dict.update({<span class="hljs-string">"JS Framework"</span>: <span class="hljs-string">"React/Next"</span>})

print(stack_dict)
<span class="hljs-comment"># {'frontend': 'JavaScript', 'backend': 'Node JS', 'markup': 'HTML and JSX', 'styling': 'CSS', 'JS Framework': 'React/Next'}</span>
</code></pre>
<p>The <code>update()</code> also overwrites an existing value if it's different:</p>
<pre><code class="lang-py">stack_dict.update({<span class="hljs-string">"backend"</span>: <span class="hljs-string">"Django"</span>})

print(stack_dict)
<span class="hljs-comment"># {'frontend': 'JavaScript', 'backend': 'Django', 'markup': 'HTML and JSX'}</span>
</code></pre>
<h3 id="heading-how-to-add-to-a-dictionary-in-python-using-the-if-statement">How to Add to a Dictionary in Python Using the <code>if</code> Statement</h3>
<p>If you don't want an entry to be overwritten even if it already exists, you can use an <code>if</code> statement. You can do it with this syntax:</p>
<pre><code class="lang-py"><span class="hljs-keyword">if</span> <span class="hljs-string">"value"</span> <span class="hljs-keyword">not</span> it dict.keys():
    dict[<span class="hljs-string">"key"</span>] = <span class="hljs-string">"value"</span>
</code></pre>
<p>I want to add a "CSS Framework" key with a value of "Tailwind CSS" to the stack dictionary, so I'm going to do that with the help of this syntax:</p>
<pre><code class="lang-py"><span class="hljs-keyword">if</span> <span class="hljs-string">"Tailwind CSS"</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> stack_dict.keys():
    stack_dict[<span class="hljs-string">"CSS Framework"</span>] = <span class="hljs-string">"Tailwind CSS"</span>

print(stack_dict)
<span class="hljs-comment"># {'frontend': 'JavaScript', 'backend': 'Node JS', 'markup': 'HTML and JSX', 'styling': 'CSS', 'JS Framework': 'React/Next', 'CSS Framework': 'Tailwind CSS'}</span>
</code></pre>
<p>If the entry is already in the dictionary, it won't be added in there:</p>
<pre><code class="lang-py"><span class="hljs-keyword">if</span> <span class="hljs-string">"HTML and JSX"</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> stack_dict.keys():
    stack_dict[<span class="hljs-string">"markup"</span>] = <span class="hljs-string">"HTML and JSX"</span>

print(stack_dict)
<span class="hljs-comment"># {'frontend': 'JavaScript', 'backend': 'Node JS', 'markup': 'HTML and JSX', 'styling': 'CSS', 'JS Framework': 'React/Next'}</span>
</code></pre>
<p>If you don't feel like using an <code>if</code> statement to add to the dictionary, you can do the same thing with <code>try…except…</code>:</p>
<pre><code class="lang-py"><span class="hljs-keyword">try</span>:
  stack_dict[<span class="hljs-string">"Deployment"</span>] = <span class="hljs-string">"Anywhere possible"</span>
<span class="hljs-keyword">except</span>:
  print(<span class="hljs-string">"An exception occurred"</span>)

print(stack_dict)
<span class="hljs-comment"># {'frontend': 'JavaScript', 'backend': 'Node JS', 'markup': 'HTML and JSX', 'styling': 'CSS', 'JS Framework': 'React/Next', 'Deployment': 'Anywhere possible'}</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article took you through three different ways to add to a dictionary in Python:</p>
<ul>
<li>mapping a key to the dictionary </li>
<li>using the update() method</li>
<li>using an if statement </li>
</ul>
<p>We even looked at how you can add to a dictionary with the <code>try…except…</code> expression.</p>
<p>Thank you for reading.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Dictionary Comprehension in Python – Dict Comprehensions Explained ]]>
                </title>
                <description>
                    <![CDATA[ You can use Dictionaries in Python to store data in key and value pairs.  And you can use dictionary comprehension to create a new dictionary from an already existing one.  When creating a new dictionary using dictionary comprehension, you can perfor... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/dictionary-comprehension-in-python-dict-comprehensions-explained/</link>
                <guid isPermaLink="false">66b0a295b30dd4d00547bb8a</guid>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Fri, 16 Sep 2022 18:47:35 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/element5-digital-OyCl7Y4y0Bk-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You can use <a target="_blank" href="https://www.freecodecamp.org/news/python-add-to-dictionary-adding-an-item-to-a-dict/">Dictionaries</a> in Python to store data in key and value pairs. </p>
<p>And you can use dictionary comprehension to create a new dictionary from an already existing one. </p>
<p>When creating a new dictionary using dictionary comprehension, you can perform various operations using expressions to determine the data (key and/or value) that will be stored in the new dictionary. </p>
<p>In this article, you'll learn how to create dictionaries in Python using dictionary comprehension. You'll also see various expressions that you can use to modify the data to be stored in the new dictionary. </p>
<p>Let's get started!</p>
<h2 id="heading-how-to-use-dictionary-comprehension-in-python">How to Use Dictionary Comprehension in Python</h2>
<p>Before we take a look at some examples, here's what the syntax for dictionary comprehension looks like:</p>
<pre><code class="lang-txt">new_dictionary = {key: value for (key,value) in iterable}
</code></pre>
<p>In the syntax above, <code>key</code> and <code>value</code> represent the key and value in the initial dictionary. Whatever operation you carry out on them determines the keys/values in the new dictionary — you'll understand this better soon with some examples. </p>
<p>The <code>key</code> and <code>value</code> in parenthesis – <code>(key, value)</code> – are still the same as the ones we mentioned above. In this case, they are used in a <code>for</code> loop. </p>
<p>So whatever operation you perform on <code>key</code> and <code>value</code> will be used by the loop to apply that operation on every item the operation is associated with in the initial dictionary.</p>
<p><code>iterable</code>, in the syntax, denotes an iterable object. In our case, it denotes the initial dictionary.</p>
<p>Let's look at some examples to help you understand the explanations above.</p>
<pre><code class="lang-python">items_in_cm = {<span class="hljs-string">'pen'</span>: <span class="hljs-number">40</span>, <span class="hljs-string">'book'</span>: <span class="hljs-number">50</span>, <span class="hljs-string">'keyboard'</span>: <span class="hljs-number">60</span>}
</code></pre>
<p>In the code above, we created a dictionary with three items. The keys are the names of the items while the values are the length of these items in centimeters. </p>
<p>Using a dictionary comprehension, we'll create a new dictionary with the length of each item in meters. </p>
<p>Here's how it works:</p>
<pre><code class="lang-python">items_in_cm = {<span class="hljs-string">'pen'</span>: <span class="hljs-number">40</span>, <span class="hljs-string">'book'</span>: <span class="hljs-number">50</span>, <span class="hljs-string">'keyboard'</span>: <span class="hljs-number">60</span>}

items_in_meters = {key: value/<span class="hljs-number">100</span> <span class="hljs-keyword">for</span> (key, value) <span class="hljs-keyword">in</span> items_in_cm.items()}

print(items_in_meters)
<span class="hljs-comment"># {'pen': 0.4, 'book': 0.5, 'keyboard': 0.6}</span>
</code></pre>
<p>What to look out for is in the second line above: <code>items_in_meters = {key: value/100 for (key, value) in items_in_cm.items()}</code></p>
<p>Let's break it down.</p>
<p>The first part has this: <code>key: value/100</code>. This implies that every <code>value</code> in the dictionary is to be divided by 100. </p>
<p>But the dictionary comprehension is yet to understand where to apply the command above. </p>
<p>This leads us to the second part: <code>for (key, value) in items_in_cm.items()</code>. This part the code has a <code>for</code> loop that takes two parameters — <code>key</code> and <code>value</code>. </p>
<p>So this will run through every key and value in the <code>items_in_cm</code> dictionary and divide each value by 100. </p>
<p>We are able to access the items in that dictionary using the <code>items()</code> method which returns every key and value pair in a dictionary. </p>
<p>Printing the new dictionary (<code>items_in_meters</code>), we have this: <code>{'pen': 0.4, 'book': 0.5, 'keyboard': 0.6}</code>. Every value in the new dictionary has been divided by 100. </p>
<p>You'll notice that we only altered the data in the dictionary's values. You can also modify the keys. Here's an example: </p>
<pre><code class="lang-python">items_in_cm = {<span class="hljs-string">'pen'</span>: <span class="hljs-number">40</span>, <span class="hljs-string">'book'</span>: <span class="hljs-number">50</span>, <span class="hljs-string">'keyboard'</span>: <span class="hljs-number">60</span>}

items_in_meters = {key + <span class="hljs-string">' in meters'</span>: value/<span class="hljs-number">100</span> <span class="hljs-keyword">for</span> (key, value) <span class="hljs-keyword">in</span> items_in_cm.items()}

print(items_in_meters)
<span class="hljs-comment"># {'pen in meters': 0.4, 'book in meters': 0.5, 'keyboard in meters': 0.6}</span>
</code></pre>
<p>In the example above, we added a string to every key in the dictionary comprehension: <code>key + ' in meters'</code>. </p>
<h2 id="heading-how-to-use-conditional-statements-in-dictionary-comprehension-in-python">How to Use Conditional Statements in Dictionary Comprehension in Python</h2>
<p>In this section and the next, you'll learn about other expressions that you can use to modify the items stored in dictionaries created using dictionary comprehension. </p>
<p>We'll start with conditional statements.</p>
<pre><code class="lang-python">developers = {<span class="hljs-string">'Jane'</span>: <span class="hljs-string">'Python'</span>, <span class="hljs-string">'Jade'</span>: <span class="hljs-string">'JavaScript'</span>, <span class="hljs-string">'John'</span>: <span class="hljs-string">'Python'</span>, <span class="hljs-string">'Doe'</span>: <span class="hljs-string">'JavaScript'</span>}

python_developers = {key: value <span class="hljs-keyword">for</span> (key, value) <span class="hljs-keyword">in</span> developers.items() <span class="hljs-keyword">if</span> value == <span class="hljs-string">'Python'</span>}

print(python_developers)
<span class="hljs-comment"># {'Jane': 'Python', 'John': 'Python'}</span>
</code></pre>
<p>In the example above, we created a dictionary called <code>developers</code> which stores a list of developers with their favorite languages: <code>{'Jane': 'Python', 'Jade': 'JavaScript', 'John': 'Python', 'Doe': 'JavaScript'}</code>.</p>
<p>In the dictionary comprehension, we added an expression at the end: <code>if value == 'Python'</code>. This will scan through and return all the items whose <code>value</code> has a value of 'Python'. </p>
<p>When printed out, we have this in the console: <code>{'Jane': 'Python', 'John': 'Python'}</code>. </p>
<p>We can also use an <code>if/else</code> statement in dictionary comprehensions. Here's an example:</p>
<pre><code class="lang-python">random_items = {<span class="hljs-string">'monitor'</span>: <span class="hljs-number">100</span>, <span class="hljs-string">'pen'</span>: <span class="hljs-number">40</span>, <span class="hljs-string">'keyboard'</span>: <span class="hljs-number">60</span>, <span class="hljs-string">'pencil'</span>: <span class="hljs-number">30</span>}

items_length_check = {key: (<span class="hljs-string">'above 50'</span> <span class="hljs-keyword">if</span> value &gt; <span class="hljs-number">50</span> <span class="hljs-keyword">else</span> <span class="hljs-string">'below 50'</span>) <span class="hljs-keyword">for</span> (key, value) <span class="hljs-keyword">in</span> random_items.items()}

print(items_length_check)
<span class="hljs-comment"># {'monitor': 'above 50', 'pen': 'below 50', 'keyboard': 'above 50', 'pencil': 'below 50'}</span>
</code></pre>
<p>Using an <code>if/else</code> statement above, we modified the values in the new dictionary. The <code>value</code> for each item will be "above 50" if the value in the initial dictionary is above 50 and "below 50" if less than 50.</p>
<p>The code in the dictionary comprehension is starting to look bulky. We'll clean it up in the next section using a function. </p>
<h2 id="heading-how-to-use-a-function-in-dictionary-comprehension-in-python">How to Use a Function in Dictionary Comprehension in Python</h2>
<p>When using dictionary comprehension, you can use functions to replace/extract logic that should go into the curly brackets of the dictionary comprehension. This help keep the code neat and readable. </p>
<pre><code class="lang-python">random_items = {<span class="hljs-string">'monitor'</span>: <span class="hljs-number">100</span>, <span class="hljs-string">'pen'</span>: <span class="hljs-number">40</span>, <span class="hljs-string">'keyboard'</span>: <span class="hljs-number">60</span>, <span class="hljs-string">'pencil'</span>: <span class="hljs-number">30</span>}

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_length</span>(<span class="hljs-params">value</span>):</span>
    <span class="hljs-keyword">if</span> value &gt;<span class="hljs-number">50</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-string">'above 50'</span>
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-string">'below 50'</span>

items_length_check = {key: check_length(value) <span class="hljs-keyword">for</span> (key, value) <span class="hljs-keyword">in</span> random_items.items()}


print(items_length_check)
<span class="hljs-comment"># {'monitor': 'above 50', 'pen': 'below 50', 'keyboard': 'above 50', 'pencil': 'below 50'}</span>
</code></pre>
<p>The example above is similar to the one in the last section. </p>
<p>We made one major change — extracting the logic in the dictionary comprehension and putting it in a function. That is:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_length</span>(<span class="hljs-params">value</span>):</span>
    <span class="hljs-keyword">if</span> value &gt;<span class="hljs-number">50</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-string">'above 50'</span>
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-string">'below 50'</span>
</code></pre>
<p>We then put the function name in the dictionary comprehension: <code>items_length_check = {key: check_length(value) for (key, value) in random_items.items()}</code>.</p>
<p>When the code in the dictionary comprehension runs, the function is fired. </p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about dictionary comprehension in Python. You can use it to create new dictionaries from existing ones.</p>
<p>We saw the syntax and how to use dictionary comprehension.</p>
<p>We also saw examples that showed how to use conditional statements and functions when working with dictionary comprehension. </p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Sort Dictionary by Value in Python – How to Sort a Dict ]]>
                </title>
                <description>
                    <![CDATA[ In Python, a dictionary is a fat structure that is unordered by default. So, sometimes, you'll want to sort dictionaries by key or value to make queries easier. The problem is that sorting a dictionary by value is never a straightforward thing to do.... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/sort-dictionary-by-value-in-python/</link>
                <guid isPermaLink="false">66adf218febac312b73075ce</guid>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Tue, 13 Sep 2022 15:16:42 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/sortDictByValue.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In Python, a dictionary is a fat structure that is unordered by default. So, sometimes, you'll want to sort dictionaries by key or value to make queries easier.</p>
<p>The problem is that sorting a dictionary by value is never a straightforward thing to do. That’s because Python doesn’t have an inbuilt method to do it.</p>
<p>However, I figured out a way to sort dictionaries by value, and that’s what I’m going to show you how to do in this article.</p>
<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><a class="post-section-overview" href="#heading-how-to-sort-data-with-the-sorted-method">How to Sort Data with the <code>sorted()</code> Method</a></li>
<li><a class="post-section-overview" href="#heading-how-the-sorted-method-works">How the <code>sorted()</code> Method Works</a><ul>
<li><a class="post-section-overview" href="#heading-parameters-of-the-sorted-method">Parameters of the <code>sorted()</code> Method</a>  </li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-sort-a-dictionary-with-the-sorted-method">How to Sort a Dictionary with the <code>sorted()</code> Method</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-convert-the-resulting-list-to-a-dictionary">How to Convert the Resulting List to a Dictionary</a></li>
<li><a class="post-section-overview" href="#heading-how-to-sort-the-dictionary-by-value-in-ascending-or-descending-order">How to Sort the Dictionary by Value in Ascending or Descending Order</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-how-to-sort-data-with-the-sorted-method">How to Sort Data with the <code>sorted()</code> Method</h2>
<p>The <code>sorted()</code> method sorts iterable data such as lists, tuples, and dictionaries. But it sorts by key only. </p>
<p>The <code>sorted()</code> method puts the sorted items in a list. That’s another problem we have to solve, because we want the sorted dictionary to remain a dictionary.</p>
<p>For instance, <code>sorted()</code> arranged the list below in alphabetical order:</p>
<pre><code class="lang-py">persons = [<span class="hljs-string">'Chris'</span>, <span class="hljs-string">'Amber'</span>, <span class="hljs-string">'David'</span>, <span class="hljs-string">'El-dorado'</span>, <span class="hljs-string">'Brad'</span>, <span class="hljs-string">'Folake'</span>]
sortedPersons = sorted(persons)

print(sortedPersons)
<span class="hljs-comment"># Output: ['Amber', 'Brad', 'Chris', 'David', 'El-dorado', 'Folake']</span>
</code></pre>
<p>And the <code>sorted()</code> method sorts the numbers in the tuple below in ascending order:</p>
<pre><code class="lang-py">numbers = (<span class="hljs-number">14</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">4</span>, <span class="hljs-number">2</span>, <span class="hljs-number">9</span>, <span class="hljs-number">8</span>, <span class="hljs-number">10</span>, <span class="hljs-number">13</span>, <span class="hljs-number">12</span>)
sortedNumbers = sorted(numbers)

print(sortedNumbers)
<span class="hljs-comment"># Output: [1, 2, 3, 4, 8, 9, 10, 12, 13, 14]</span>
</code></pre>
<p>If you use the <code>sorted()</code> method with a dictionary, only the keys will be returned and as usual, it will be in a list:</p>
<pre><code class="lang-py">my_dict = { <span class="hljs-string">'num6'</span>: <span class="hljs-number">6</span>, <span class="hljs-string">'num3'</span>: <span class="hljs-number">3</span>, <span class="hljs-string">'num2'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'num4'</span>: <span class="hljs-number">4</span>, <span class="hljs-string">'num1'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'num5'</span>: <span class="hljs-number">5</span>}
sortedDict = sorted(my_dict)

print(sortedDict)
<span class="hljs-comment"># ['num1', 'num2', 'num3', 'num4', 'num5', 'num6']</span>
</code></pre>
<p>This is not the behavior you want. You want the dictionary to be sorted by value and remain a dictionary. That’s what I’m going to show you next.</p>
<h2 id="heading-how-the-sorted-method-works">How the <code>sorted()</code> Method Works</h2>
<p>To sort a dictionary, we are still going to use the sorted function, but in a more complicated way. Don’t worry, I will explain everything you need to know. </p>
<p>Since we are still going to use the <code>sorted()</code> method, then it’s time to explain the <code>sorted()</code> method in detail.</p>
<h3 id="heading-parameters-of-the-sorted-method">Parameters of the <code>sorted()</code> Method</h3>
<p>The <code>sorted()</code> method can accept up to 3 parameters:</p>
<ul>
<li><p>iterable – the data to iterate over. It could be a tuple, list, or dictionary. </p>
</li>
<li><p>key – an optional value, the function that helps you to perform a custom sort operation.</p>
</li>
<li><p>reverse – another optional value. It helps you arrange the sorted data in ascending or descending order</p>
</li>
</ul>
<p>If you guess it right, the key parameter is what we’ll pass into the <code>sorted()</code> method to get the dictionary sorted by value. </p>
<p>Now, it’s time to sort our dictionary by value and make sure it remains a dictionary.</p>
<h2 id="heading-how-to-sort-a-dictionary-with-the-sorted-method">How to Sort a Dictionary with the <code>sorted()</code> Method</h2>
<p>To correctly sort a dictionary by value with the <code>sorted()</code> method, you will have to do the following:</p>
<ul>
<li>pass the dictionary to the <code>sorted()</code> method as the first value </li>
<li>use the <code>items()</code> method on the dictionary to retrieve its keys and values</li>
<li>write a lambda function to get the values retrieved with the <code>item()</code> method</li>
</ul>
<p>Here’s an example:</p>
<pre><code class="lang-py">footballers_goals = {<span class="hljs-string">'Eusebio'</span>: <span class="hljs-number">120</span>, <span class="hljs-string">'Cruyff'</span>: <span class="hljs-number">104</span>, <span class="hljs-string">'Pele'</span>: <span class="hljs-number">150</span>, <span class="hljs-string">'Ronaldo'</span>: <span class="hljs-number">132</span>, <span class="hljs-string">'Messi'</span>: <span class="hljs-number">125</span>}

sorted_footballers_by_goals = sorted(footballers_goals.items(), key=<span class="hljs-keyword">lambda</span> x:x[<span class="hljs-number">1</span>])
print(sorted_footballers_by_goals)
</code></pre>
<p>As I said earlier, we have to get those values of the dictionary so we can sort the dictionary by values. That’s why you can see 1 in the lambda function. </p>
<p>1 represents the indexes of the values. The keys are 0. Remember that a programmer starts counting from 0, not 1.</p>
<p>With that code above, I got the result below:</p>
<pre><code class="lang-py"><span class="hljs-comment"># [('Cruyff', 104), ('Eusebio', 120), ('Messi', 125), ('Ronaldo', 132), ('Pele', 150)]</span>
</code></pre>
<p>Here’s the full code so you don’t get confused:</p>
<pre><code class="lang-py">footballers_goals = {<span class="hljs-string">'Eusebio'</span>: <span class="hljs-number">120</span>, <span class="hljs-string">'Cruyff'</span>: <span class="hljs-number">104</span>, <span class="hljs-string">'Pele'</span>: <span class="hljs-number">150</span>, <span class="hljs-string">'Ronaldo'</span>: <span class="hljs-number">132</span>, <span class="hljs-string">'Messi'</span>: <span class="hljs-number">125</span>}

sorted_footballers_by_goals = sorted(footballers_goals.items(), key=<span class="hljs-keyword">lambda</span> x:x[<span class="hljs-number">1</span>])
print(sorted_footballers_by_goals)

<span class="hljs-comment"># [('Cruyff', 104), ('Eusebio', 120), ('Messi', 125), ('Ronaldo', 132), ('Pele', 150)]</span>
</code></pre>
<p>You can see the dictionary has been sorted by values in ascending order. You can also sort it in descending order. But we’ll look at that later because we still have a problem with the result we got.</p>
<p>The problem is that the dictionary is not a dictionary anymore. The individual keys and values were put in a tuple and further condensed into a list. Remember that whatever you get as the result of the <code>sorted()</code> method is put in a list. </p>
<p>We’ve been able to sort the items in the dictionary by value. What’s left is converting it back to a dictionary. </p>
<h3 id="heading-how-to-convert-the-resulting-list-to-a-dictionary">How to Convert the Resulting List to a Dictionary</h3>
<p>To convert the resulting list to a dictionary, you don’t need to write another complicated function or a loop. You just need to pass the variable saving the resulting list into the <code>dict()</code> method.  </p>
<pre><code class="lang-py">converted_dict = dict(sorted_footballers_by_goals)
print(converted_dict)
<span class="hljs-comment"># Output: {'Cruyff': 104, 'Eusebio': 120, 'Messi': 125, 'Ronaldo': 132, 'Pele': 150}</span>
</code></pre>
<p>Remember we saved the sorted dictionary in the variable named <code>sorted_footballers_by_goals</code>, so it’s the variable we have to pass to <code>dict()</code>.</p>
<p>The full code looks like this:</p>
<pre><code class="lang-py">footballers_goals = {<span class="hljs-string">'Eusebio'</span>: <span class="hljs-number">120</span>, <span class="hljs-string">'Cruyff'</span>: <span class="hljs-number">104</span>, <span class="hljs-string">'Pele'</span>: <span class="hljs-number">150</span>, <span class="hljs-string">'Ronaldo'</span>: <span class="hljs-number">132</span>, <span class="hljs-string">'Messi'</span>: <span class="hljs-number">125</span>}

sorted_footballers_by_goals = sorted(footballers_goals.items(), key=<span class="hljs-keyword">lambda</span> x:x[<span class="hljs-number">1</span>])
converted_dict = dict(sorted_footballers_by_goals)

print(converted_dict)
<span class="hljs-comment"># Output: {'Cruyff': 104, 'Eusebio': 120, 'Messi': 125, 'Ronaldo': 132, 'Pele': 150}</span>
</code></pre>
<p>That’s it! We’ve been able to sort the items in the dictionary and convert them back to a dictionary. We’ve just had our cake and ate it as well!</p>
<h3 id="heading-how-to-sort-the-dictionary-by-value-in-ascending-or-descending-order">How to Sort the Dictionary by Value in Ascending or Descending Order</h3>
<p>Remember the <code>sorted()</code> method accepts a third value called <code>reverse</code>. </p>
<p><code>reverse</code> with a value of <code>True</code> will arrange the sorted dictionary in descending order.</p>
<pre><code class="lang-py">footballers_goals = {<span class="hljs-string">'Eusebio'</span>: <span class="hljs-number">120</span>, <span class="hljs-string">'Cruyff'</span>: <span class="hljs-number">104</span>, <span class="hljs-string">'Pele'</span>: <span class="hljs-number">150</span>, <span class="hljs-string">'Ronaldo'</span>: <span class="hljs-number">132</span>, <span class="hljs-string">'Messi'</span>: <span class="hljs-number">125</span>}

sorted_footballers_by_goals = sorted(footballers_goals.items(), key=<span class="hljs-keyword">lambda</span> x:x[<span class="hljs-number">1</span>], reverse=<span class="hljs-literal">True</span>)
converted_dict = dict(sorted_footballers_by_goals)

print(converted_dict)
<span class="hljs-comment"># Output: {'Pele': 150, 'Ronaldo': 132, 'Messi': 125, 'Eusebio': 120, 'Cruyff': 104}</span>
</code></pre>
<p>You can see the output is reversed because we passed <code>reverse=True</code> to the <code>sorted()</code> method.</p>
<p>If you don’t set <code>reverse</code> at all or you set its value to false, the dictionary will be arranged in ascending order. That’s the default.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Congratulations. You can now sort a dictionary by value despite not having a built-in method or function to use in Python.</p>
<p>However, there’s something that raised my curiosity when I was preparing to write this article. Remember we were able to use <code>sorted()</code> directly on a dictionary. This got us a list as the result, though we only got the keys and not the values.</p>
<p>What if we convert that list to a dictionary with the <code>dict()</code> method? Do you think we can get the desired result? Let's see:</p>
<pre><code class="lang-py">my_dict = { <span class="hljs-string">'num6'</span>: <span class="hljs-number">6</span>, <span class="hljs-string">'num3'</span>: <span class="hljs-number">3</span>, <span class="hljs-string">'num2'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'num4'</span>: <span class="hljs-number">4</span>, <span class="hljs-string">'num1'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'num5'</span>: <span class="hljs-number">5</span>}
sortedDict = sorted(my_dict)

converted_dict = dict(sortedDict)
print(converted_dict)
<span class="hljs-string">"""
Output: 
dict_by_value.py
Traceback (most recent call last):
  File "sort_dict_by_value.py", line 17, in &lt;module&gt;
    converted_dict = dict(sortedDict)
ValueError: dictionary update sequence element #0 has length 4; 2 is required
"""</span>
</code></pre>
<p>We got an error! That’s because if you want to create a dictionary from a list, you have to use dictionary comprehension. And if you use dictionary comprehension for this type of data, you’d have to specify one value for all the entries. That would defy the purpose of sorting a dictionary by value, so it's not what we want.</p>
<p>If you want to learn more about dictionary comprehension, you should <a target="_blank" href="https://www.freecodecamp.org/news/dictionary-comprehension-in-python-explained-with-examples/">read this article</a>.</p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Dictionary Methods – Dictionaries in Python ]]>
                </title>
                <description>
                    <![CDATA[ In Python, a dictionary is one of the core data structures. It is a sequence of key-value pairs separated by commas and surrounded by curly braces.  If you’re familiar with JavaScript, Python dictionaries are like JavaScript objects. Python provides... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-dictionary-methods-dictionaries-in-python/</link>
                <guid isPermaLink="false">66adf1d1f452caf50fb1fe15</guid>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Thu, 28 Jul 2022 15:32:21 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/python_dict.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In Python, a dictionary is one of the core data structures. It is a sequence of key-value pairs separated by commas and surrounded by curly braces. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/keyvalue.png" alt="keyvalue" width="600" height="400" loading="lazy"></p>
<p>If you’re familiar with JavaScript, Python dictionaries are like JavaScript objects.</p>
<p>Python provides more than 10 methods for working with dictionaries.</p>
<p>In this article, I will show you how to create a dictionary in Python and work with it using those methods.</p>
<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><a class="post-section-overview" href="#how-to-create-a-dictionary-in-Python">How to Create a Dictionary in Python</a></li>
<li><a class="post-section-overview" href="#methods-forworking-with-python-dictionaries">Methods for Working with Python Dictionaries</a><ul>
<li><a class="post-section-overview" href="#how-to-use-the-get-dictionary-method">How to Use the <code>get()</code> Dictionary Method</a></li>
<li><a class="post-section-overview" href="#how-to-use-the-items-dictionary-method">How to Use the <code>items()</code> Dictionary Method</a></li>
<li><a class="post-section-overview" href="#how-to-use-the-keys-dictionary-method">How to Use the <code>keys()</code> Dictionary Method</a></li>
<li><a class="post-section-overview" href="#how-to-use-the-values-dictionary-method">How to Use the <code>values()</code> Dictionary Method</a></li>
<li><a class="post-section-overview" href="#how-to-use-the-pop-dictionary-method">How to Use the <code>pop()</code> Dictionary Method</a></li>
<li><a class="post-section-overview" href="#how-to-use-the-popitem-dictionary-method">How to Use the <code>popitem()</code> Dictionary Method</a></li>
<li><a class="post-section-overview" href="#how-to-use-the-update-dictionary-method">How to Use the <code>update()</code> Dictionary Method</a></li>
<li><a class="post-section-overview" href="#how-to-use-the-copy-dictionary-method">How to Use the <code>copy()</code> Dictionary Method</a></li>
<li><a class="post-section-overview" href="#how-to-use-the-clear-dictionary-method">How to Use the <code>clear()</code> Dictionary Method</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-how-to-create-a-dictionary-in-python">How to Create a Dictionary in Python</h2>
<p>To create a dictionary, you open up a curly brace and put the data in a key-value pair separated by commas.</p>
<p>The basic syntax of a dictionary looks like this:</p>
<pre><code class="lang-py">demo_dict = {
<span class="hljs-string">"key1"</span>: <span class="hljs-string">"value1"</span>,
<span class="hljs-string">"key2"</span>: <span class="hljs-string">"value2"</span>, 
<span class="hljs-string">"key3"</span>: <span class="hljs-string">"value3"</span>
}
</code></pre>
<p>Note that the values can be of any data type and can be duplicated, but the key must not be duplicated. If the keys are duplicated, you will get an invalid syntax error.</p>
<h2 id="heading-methods-for-working-with-python-dictionaries">Methods for Working with Python Dictionaries</h2>
<p>I will be working with the dictionary below to show you how the dictionary methods work:</p>
<pre><code class="lang-py">first_dict = {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"freeCodeCamp"</span>, 
    <span class="hljs-string">"founder"</span>: <span class="hljs-string">"Quincy Larson"</span>,
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"charity"</span>, 
    <span class="hljs-string">"age"</span>: <span class="hljs-number">8</span>, 
    <span class="hljs-string">"price"</span>: <span class="hljs-string">"free"</span>, 
    <span class="hljs-string">"work-style"</span>: <span class="hljs-string">"remote"</span>,
}
</code></pre>
<h3 id="heading-how-to-use-the-get-dictionary-method">How to Use the <code>get()</code> Dictionary Method</h3>
<p>The get method returns the value of a specified key. </p>
<p>In the code below, I was able to get the founder of freeCodeCamp by passing the <code>founder</code> key inside the <code>get()</code> method:</p>
<pre><code class="lang-py">first_dict = {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"freeCodeCamp"</span>, 
    <span class="hljs-string">"founder"</span>: <span class="hljs-string">"Quincy Larson"</span>,
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"charity"</span>, 
    <span class="hljs-string">"age"</span>: <span class="hljs-number">8</span>, 
    <span class="hljs-string">"price"</span>: <span class="hljs-string">"free"</span>, 
    <span class="hljs-string">"work-style"</span>: <span class="hljs-string">"remote"</span>,
}

founder = first_dict.get(<span class="hljs-string">"founder"</span>)
print(founder)

<span class="hljs-comment"># Output: Quincy Larson</span>
</code></pre>
<h3 id="heading-how-to-use-the-items-dictionary-method">How to Use the <code>items()</code> Dictionary Method</h3>
<p>The <code>items()</code> method returns all the entries of the dictionary in a list. In the list is a tuple representing each of the items.</p>
<pre><code class="lang-py">first_dict = {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"freeCodeCamp"</span>, 
    <span class="hljs-string">"founder"</span>: <span class="hljs-string">"Quincy Larson"</span>,
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"charity"</span>, 
    <span class="hljs-string">"age"</span>: <span class="hljs-number">8</span>, 
    <span class="hljs-string">"price"</span>: <span class="hljs-string">"free"</span>, 
    <span class="hljs-string">"work-style"</span>: <span class="hljs-string">"remote"</span>,
}

items = first_dict.items()
print(items)

<span class="hljs-comment"># Output: dict_items([('name', 'freeCodeCamp'), ('founder', 'Quincy Larson'), ('type', 'charity'), ('age', 8), ('price', 'free'), ('work-style', 'remote')])</span>
</code></pre>
<h3 id="heading-how-to-use-the-keys-dictionary-method">How to Use the <code>keys()</code> Dictionary Method</h3>
<p>The <code>keys()</code> returns all the keys in the dictionary. It returns the keys in a tuple – another Python data structure.</p>
<pre><code class="lang-py">first_dict = {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"freeCodeCamp"</span>, 
    <span class="hljs-string">"founder"</span>: <span class="hljs-string">"Quincy Larson"</span>,
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"charity"</span>, 
    <span class="hljs-string">"age"</span>: <span class="hljs-number">8</span>, 
    <span class="hljs-string">"price"</span>: <span class="hljs-string">"free"</span>, 
    <span class="hljs-string">"work-style"</span>: <span class="hljs-string">"remote"</span>,
}

dict_keys = first_dict.keys()
print(dict_keys)

<span class="hljs-comment"># Output: dict_keys(['name', 'founder', 'type', 'age', 'price', 'work-style'])</span>
</code></pre>
<h3 id="heading-how-to-use-the-values-dictionary-method">How to Use the <code>values()</code> Dictionary Method</h3>
<p>The values method accesses all the values in a dictionary. Like the <code>keys()</code> method, it returns the values in a tuple.</p>
<pre><code class="lang-py">first_dict = {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"freeCodeCamp"</span>, 
    <span class="hljs-string">"founder"</span>: <span class="hljs-string">"Quincy Larson"</span>,
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"charity"</span>, 
    <span class="hljs-string">"age"</span>: <span class="hljs-number">8</span>, 
    <span class="hljs-string">"price"</span>: <span class="hljs-string">"free"</span>, 
    <span class="hljs-string">"work-style"</span>: <span class="hljs-string">"remote"</span>,
}

dict_values = first_dict.values()
print(dict_values)

<span class="hljs-comment"># Output: dict_values(['freeCodeCamp', 'Quincy Larson', 'charity', 8, 'free', 'remote'])</span>
</code></pre>
<h3 id="heading-how-to-use-the-pop-dictionary-method">How to Use the <code>pop()</code> Dictionary Method</h3>
<p>The <code>pop()</code> method removes a key-value pair from the dictionary. To make it work, you need to specify the key inside its parentheses. </p>
<pre><code class="lang-py">first_dict = {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"freeCodeCamp"</span>, 
    <span class="hljs-string">"founder"</span>: <span class="hljs-string">"Quincy Larson"</span>,
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"charity"</span>, 
    <span class="hljs-string">"age"</span>: <span class="hljs-number">8</span>, 
    <span class="hljs-string">"price"</span>: <span class="hljs-string">"free"</span>, 
    <span class="hljs-string">"work-style"</span>: <span class="hljs-string">"remote"</span>,
}

first_dict.pop(<span class="hljs-string">"work-style"</span>)
print(first_dict)

<span class="hljs-comment"># Output: {'name': 'freeCodeCamp', 'founder': 'Quincy Larson', 'type': 'charity', 'age': 8, 'price': 'free'}</span>
</code></pre>
<p>You can see the <code>work-style</code> key and its value have been removed from the dictionary.</p>
<h3 id="heading-how-to-use-the-popitem-dictionary-method">How to Use the <code>popitem()</code> Dictionary Method</h3>
<p>The <code>popitem()</code> method works like the <code>pop()</code> method. The difference is that it removes the last item in the dictionary.</p>
<pre><code class="lang-py">first_dict = {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"freeCodeCamp"</span>, 
    <span class="hljs-string">"founder"</span>: <span class="hljs-string">"Quincy Larson"</span>,
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"charity"</span>, 
    <span class="hljs-string">"age"</span>: <span class="hljs-number">8</span>, 
    <span class="hljs-string">"price"</span>: <span class="hljs-string">"free"</span>, 
    <span class="hljs-string">"work-style"</span>: <span class="hljs-string">"remote"</span>,
}

first_dict.popitem()
print(first_dict)

<span class="hljs-comment"># Output: {'name': 'freeCodeCamp', 'founder': 'Quincy Larson', 'type': 'charity', 'age': 8, 'price': 'free'}</span>
</code></pre>
<p>You can see that the last key-value pair ("work-style": "remote") has been removed from the dictionary.</p>
<h3 id="heading-how-to-use-the-update-dictionary-method">How to Use the <code>update()</code> Dictionary Method</h3>
<p>The <code>update()</code> method adds an item to the dictionary. You have to specify both the key and value inside its braces and surround it with curly braces.</p>
<pre><code class="lang-py">first_dict = {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"freeCodeCamp"</span>, 
    <span class="hljs-string">"founder"</span>: <span class="hljs-string">"Quincy Larson"</span>,
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"charity"</span>, 
    <span class="hljs-string">"age"</span>: <span class="hljs-number">8</span>, 
    <span class="hljs-string">"price"</span>: <span class="hljs-string">"free"</span>, 
    <span class="hljs-string">"work-style"</span>: <span class="hljs-string">"remote"</span>,
}

first_dict.update({<span class="hljs-string">"Editor"</span>: <span class="hljs-string">"Abbey Rennemeyer"</span>})
print(first_dict)

<span class="hljs-comment"># Output: {'name': 'freeCodeCamp', 'founder': 'Quincy Larson', 'type': 'charity', 'age': 8, 'price': 'free', 'work-style': 'remote', 'Editor': 'Abbey Rennemeyer'}</span>
</code></pre>
<p>The new entry has been added to the dictionary.</p>
<h3 id="heading-how-to-use-the-copy-dictionary-method">How to Use the <code>copy()</code> Dictionary Method</h3>
<p>The <code>copy()</code> method does what its name implies – it copies the dictionary into the variable specified.</p>
<pre><code class="lang-py">first_dict = {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"freeCodeCamp"</span>, 
    <span class="hljs-string">"founder"</span>: <span class="hljs-string">"Quincy Larson"</span>,
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"charity"</span>, 
    <span class="hljs-string">"age"</span>: <span class="hljs-number">8</span>, 
    <span class="hljs-string">"price"</span>: <span class="hljs-string">"free"</span>, 
    <span class="hljs-string">"work-style"</span>: <span class="hljs-string">"remote"</span>,
}

second_dict = first_dict.copy()
print(second_dict)

<span class="hljs-comment"># Output: {'name': 'freeCodeCamp', 'founder': 'Quincy Larson', 'type': 'charity', 'age': 8, 'price': 'free', 'work-style': 'remote'}</span>
</code></pre>
<h3 id="heading-how-to-use-the-clear-dictionary-method">How to Use the <code>clear()</code> Dictionary Method</h3>
<p>The clear method removes all the entries in the dictionary.</p>
<pre><code class="lang-py">first_dict = {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"freeCodeCamp"</span>, 
    <span class="hljs-string">"founder"</span>: <span class="hljs-string">"Quincy Larson"</span>,
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"charity"</span>, 
    <span class="hljs-string">"age"</span>: <span class="hljs-number">8</span>, 
    <span class="hljs-string">"price"</span>: <span class="hljs-string">"free"</span>, 
    <span class="hljs-string">"work-style"</span>: <span class="hljs-string">"remote"</span>,
}

first_dict.clear()
print(first_dict)

<span class="hljs-comment"># Output: {}</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned how to create a Python dictionary and how to work with it using the built-in methods provided by Python.</p>
<p>If you find the article helpful, don’t hesitate to share it with friends and family.</p>
<p>Keep coding :)</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Remove a Key from a Dictionary While Iterating Over it ]]>
                </title>
                <description>
                    <![CDATA[ Python dictionaries allow you to store values in a Key and Value format. You can access the values using the key. You can also iterate through the complete dictionary to access every element. Sometimes while iterating through the dictionary, you may ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-remove-a-key-from-the-dictionary-while-iterating-over-it-definitive-guide/</link>
                <guid isPermaLink="false">66bb8ac46b3bd8d6bf25ae4a</guid>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Vikram Aruchamy ]]>
                </dc:creator>
                <pubDate>Wed, 06 Jul 2022 21:56:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/Freecodecamp_dictionary_delete_iterate.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Python dictionaries allow you to store values in a <code>Key</code> and <code>Value</code> format.</p>
<p>You can access the values using the key. You can also iterate through the complete dictionary to access every element.</p>
<p>Sometimes while iterating through the dictionary, you may need to remove a key from the dictionary.</p>
<p>This tutorial will teach you how to remove a key from a dictionary <strong>while iterating over it</strong>.</p>
<p>To remove a key directly without iterating, read the freeCodeCamp tutorial <a target="_blank" href="https://www.freecodecamp.org/news/how-to-remove-a-key-from-a-python-dictionary-delete-key-from-dict/">How to Remove a key from a Python Dictionary</a>.</p>
<h2 id="heading-how-to-create-a-dictionary">How to Create a Dictionary</h2>
<p>Let's first create a dictionary with some key-value pairs using the assignment operator.</p>
<p>To add a key to the dictionary using different methods, read <a target="_blank" href="https://www.stackvidhya.com/python-add-key-to-dictionary/">How to Add a Key to a Dictionary</a></p>
<p>After creating the dictionary, you can use the <code>for</code> loop to iterate through it and print the values to check if the dictionary has been created successfully.</p>
<p><strong>Here's the code:</strong></p>
<pre><code class="lang-python">yourdict = {
    <span class="hljs-string">"one"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-string">"two"</span>: <span class="hljs-number">2</span>,
    <span class="hljs-string">"three"</span>: <span class="hljs-number">3</span>,
    <span class="hljs-string">"four"</span>: <span class="hljs-number">4</span>,
}

<span class="hljs-keyword">for</span> key <span class="hljs-keyword">in</span> yourdict.keys():
    print(key, yourdict[key])
</code></pre>
<p>You can print the values in the dictionary as follows.</p>
<p><strong>Output:</strong></p>
<pre><code>    one <span class="hljs-number">1</span>
    two <span class="hljs-number">2</span>
    three <span class="hljs-number">3</span>
    four <span class="hljs-number">4</span>
</code></pre><p>To check if a key exists in a dictionary without iterating over it, read <a target="_blank" href="https://www.stackvidhya.com/check-if-key-exists-in-dictionary-python/">how to check if a key exists in dictionary in Python</a>.</p>
<h2 id="heading-how-to-check-the-python-version">How to Check the Python Version</h2>
<p>Python 2 and Python 3 work <em>differently</em> when you try to delete a key from a dictionary while iterating.</p>
<p>To check which version of Python you are using, use the below code snippet.</p>
<p><strong>Here's the code:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sys
print(sys.version)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code><span class="hljs-number">3.8</span><span class="hljs-number">.2</span> (<span class="hljs-keyword">default</span>, Sep  <span class="hljs-number">4</span> <span class="hljs-number">2020</span>, <span class="hljs-number">00</span>:<span class="hljs-number">03</span>:<span class="hljs-number">40</span>) [MSC v<span class="hljs-number">.1916</span> <span class="hljs-number">32</span> bit (Intel)]
</code></pre><p>You'll see whatever version you have. And now you know which version of Python you are using.</p>
<p>You can follow the appropriate methods explained below.</p>
<h2 id="heading-how-to-delete-a-key-from-a-dict-based-on-key-value-python-3">How to Delete A Key from a Dict Based on Key Value – Python 3</h2>
<p>This section teaches you how to delete a key from a dictionary using Python 3.</p>
<p>You need to convert the <code>keys</code> to a <code>list</code> using the <code>list(dict.keys())</code> and <a target="_blank" href="https://www.stackvidhya.com/iterate-through-dictionary-python/">iterate through a dictionary</a> using the <code>for</code> loop.  </p>
<p>While converting the <code>keys</code> to a <code>list</code>, Python 3 creates a <em>new copy</em> of the keys in the list. There will be no reference to the dictionary during the iteration.</p>
<p>If you do not convert it into a list, then the <a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#dict.keys">keys</a> method just returns a new view of the keys with reference to the currently iterated dictionary.</p>
<p>Now, during each iteration of the list of keys, you can check if the <code>key</code> is <em>equal to the item</em> you need to <em>delete.</em> If it is <code>True</code>, you can delete the <code>key</code> using the <code>del</code> statement.</p>
<p><strong>Here's the code:</strong></p>
<p>The below code demonstrates how to remove a key from the dictionary while iterating over it using Python 3.</p>
<pre><code class="lang-python">yourdict = {
    <span class="hljs-string">"one"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-string">"two"</span>: <span class="hljs-number">2</span>,
    <span class="hljs-string">"three"</span>: <span class="hljs-number">3</span>,
    <span class="hljs-string">"four"</span>: <span class="hljs-number">4</span>,
}

<span class="hljs-keyword">for</span> k <span class="hljs-keyword">in</span> list(yourdict.keys()):
    <span class="hljs-keyword">if</span> k == <span class="hljs-string">"four"</span>:
        <span class="hljs-keyword">del</span> yourdict[k]

yourdict
</code></pre>
<p>As you can see in the code below, the key <em>four</em> gets deleted from the dictionary while iterating through it.</p>
<p><strong>Output:</strong></p>
<pre><code>    {<span class="hljs-string">'one'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'two'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'three'</span>: <span class="hljs-number">3</span>}
</code></pre><p>If you use the <code>dict.keys()</code> method to iterate and issue a <code>del</code> statement, you’ll see the below error in Python 3.</p>
<pre><code class="lang-python">RuntimeError: dictionary changed size during iteration
</code></pre>
<h2 id="heading-how-to-delete-a-key-from-a-dict-based-on-values-python-3">How to Delete a Key from a Dict Based on Values – Python 3</h2>
<p>This section teaches you how to remove a key from a dictionary based on the value of the key while iterating over the dictionary.</p>
<p>First, you need to convert the dictionary keys to a <code>list</code> using the <code>list(dict.keys())</code> method.</p>
<p>During each iteration, you can check if the <em>value of a key</em> is equal to the desired value. If it is <code>True</code>, you can issue the <code>del</code> statement to delete the key.</p>
<pre><code class="lang-python">yourdict = {
    <span class="hljs-string">"one"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-string">"two"</span>: <span class="hljs-number">2</span>,
    <span class="hljs-string">"three"</span>: <span class="hljs-number">3</span>,
    <span class="hljs-string">"four"</span>: <span class="hljs-number">4</span>,
}

<span class="hljs-keyword">for</span> k <span class="hljs-keyword">in</span> list(yourdict.keys()):
    <span class="hljs-keyword">if</span> yourdict [k] == <span class="hljs-number">4</span>:
        <span class="hljs-keyword">del</span> yourdict[k]

print(yourdict)
</code></pre>
<p>The key <em>four</em> gets deleted based on its value <em>4</em>.</p>
<p><strong>Output:</strong></p>
<pre><code class="lang-python">{‘three’: <span class="hljs-number">3</span>, <span class="hljs-string">'two'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'one'</span>: <span class="hljs-number">1</span>}
</code></pre>
<h2 id="heading-how-to-delete-a-key-from-a-dict-based-on-the-key-python-2">How to Delete a Key from a Dict Based on the Key – Python 2</h2>
<p>This section teaches you how to remove a key from a dictionary while iterating over it using Python 2.</p>
<p>You can directly <a target="_blank" href="https://www.stackvidhya.com/iterate-through-dictionary-python/">iterate through a dictionary</a> using the <code>dict.keys()</code> method. In Python 2, the <code>dict.keys()</code> method creates a copy of the keys and iterates over the <code>copy</code> instead of iterating through the keys directly. So there will be <em>no reference</em> to the dictionary directly while iterating.</p>
<p>Now during each iteration, you can check if the item is <em>equal to the key</em> you want to delete. And if it is equal, you can issue the <code>del</code> statement. It’ll remove the key from the dictionary.</p>
<p><strong>Here's the code:</strong></p>
<p>The below code demonstrates how to remove a key from dictionary while iterating over it using Python 2.</p>
<pre><code class="lang-python">yourdict = {
    <span class="hljs-string">"one"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-string">"two"</span>: <span class="hljs-number">2</span>,
    <span class="hljs-string">"three"</span>: <span class="hljs-number">3</span>,
    <span class="hljs-string">"four"</span>: <span class="hljs-number">4</span>,
}

<span class="hljs-keyword">for</span> k <span class="hljs-keyword">in</span> yourdict.keys():
    <span class="hljs-keyword">if</span> k == <span class="hljs-string">"four"</span>:
        <span class="hljs-keyword">del</span> yourdict[k]

yourdict
</code></pre>
<p>The key <em>four</em> gets deleted, and only the other items are available in the dictionary.</p>
<p><strong>Output:</strong></p>
<pre><code>    {<span class="hljs-string">'one'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'two'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'three'</span>: <span class="hljs-number">3</span>}
</code></pre><p>This is how you can remove a key based on the key.</p>
<h2 id="heading-how-to-delete-a-key-in-a-dict-based-on-values-python-2">How to Delete a Key in a Dict Based on Values – Python 2</h2>
<p>This section teaches you how to remove a key from a dictionary based on the value of the key while iterating over the dictionary.</p>
<p>Iterate over the dictionary using the <code>dict.items()</code> method. It’ll return the key-value pair during each iteration.</p>
<p>Then you can check if the <code>value</code> of the current iteration <em>equals your desired value</em> to be removed. Then issue the <code>del</code> statement to remove the key from the dictionary.</p>
<pre><code class="lang-python">yourdict = {
    <span class="hljs-string">"one"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-string">"two"</span>: <span class="hljs-number">2</span>,
    <span class="hljs-string">"three"</span>: <span class="hljs-number">3</span>,
    <span class="hljs-string">"four"</span>: <span class="hljs-number">4</span>,
}

<span class="hljs-keyword">for</span> key, val <span class="hljs-keyword">in</span> yourdict.items():
    <span class="hljs-keyword">if</span> val == <span class="hljs-number">3</span>:
        <span class="hljs-keyword">del</span> yourdict[key]

print(yourdict)
</code></pre>
<p>The key <em>three</em> gets deleted based on its value <em>3</em>. All other items are available in the dictionary.</p>
<p><strong>Output:</strong></p>
<pre><code class="lang-python">{<span class="hljs-string">'four'</span>: <span class="hljs-number">4</span>, <span class="hljs-string">'two'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'one'</span>: <span class="hljs-number">1</span>}
</code></pre>
<h2 id="heading-why-do-python-3-and-python-2-work-differently">Why Do Python 3 and Python 2 Work Differently?</h2>
<p>When using the <code>dict.keys()</code> method, Python 3 returns a <em>view</em> of the keys. This means there is a reference to the dictionary while iterating over it. </p>
<p>On the other hand, Python 2 returns a <em>copy</em> of the keys, meaning there is NO dictionary reference while iterating it. This means that deletion will be successful without problems.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you’ve learned how to remove a key from a dictionary while iterating over it in different versions of Python – Python 2 and Python 3.</p>
<p>You’ve also learned how to delete a key based on a key or the value of a key.</p>
<p>If you liked this article, feel free to share it.</p>
<p>You can check out my other <a target="_blank" href="https://www.stackvidhya.com">Python tutorials here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Add to Dictionary – Adding an Item to a Dict ]]>
                </title>
                <description>
                    <![CDATA[ Data structures help us organize and store collections of data. Python has built-in data structures like Lists, Sets, Tuples and Dictionaries.  Each of these structures have their own syntax and methods for interacting with the data stored.  In this ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-add-to-dictionary-adding-an-item-to-a-dict/</link>
                <guid isPermaLink="false">66b0a333d7edba94d20b3bc9</guid>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Tue, 15 Mar 2022 00:33:07 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/03/dictionaary.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Data structures help us organize and store collections of data. Python has built-in data structures like Lists, Sets, Tuples and Dictionaries. </p>
<p>Each of these structures have their own syntax and methods for interacting with the data stored. </p>
<p>In this article, we'll talk about Dictionaries, their features, and how to add items to them. </p>
<h2 id="heading-how-to-create-a-dictionary-in-python">How to Create a Dictionary in Python</h2>
<p>Dictionaries are made up of key and value pairs nested in curly brackets. Here's an example of a Dictionary:</p>
<pre><code class="lang-python">devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">120</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"JavaScript"</span>
}
print(devBio)
<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 120, 'language': 'JavaScript'}</span>
</code></pre>
<p>In the code above, we created a dictionary called <code>devBio</code> with information about a developer – the developer's age is quite overwhelming.</p>
<p>Each key in the dictionary – <code>name</code>, <code>age</code> and <code>language</code> – has a corresponding value. A comma separates each key and value pair from another. Omitting the comma throws an error your way.</p>
<p>Before we dive into how we can add items to our dictionaries, let's have a look at some of the features of a dictionary. This will help you easily distinguish them from other data structures in Python. </p>
<h2 id="heading-features-of-a-dictionary">Features of a Dictionary</h2>
<p>Here are some of the features of a dictionary in Python:</p>
<h3 id="heading-duplicate-keys-are-not-allowed">Duplicate Keys Are Not Allowed</h3>
<p>If we create a dictionary that has two or multiple identical keys in it, the last key out of them will override the rest. Here's an example: </p>
<pre><code class="lang-python">devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Vincent"</span>,
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Chikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">120</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"JavaScript"</span>
}
print(devBio)
<span class="hljs-comment"># {'name': 'Chikara', 'age': 120, 'language': 'JavaScript'}</span>
</code></pre>
<p>We created three keys with an identical key name of <code>name</code>. When we printed our dictionary to the console, the last key having a value of "Chikara" overwrote the rest.</p>
<p>Let's see the next feature.</p>
<h3 id="heading-items-in-a-dictionary-are-changeable">Items in a Dictionary Are Changeable</h3>
<p>After assigning an item to a dictionary, you can change its value to something different. </p>
<pre><code class="lang-python">devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">120</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"JavaScript"</span>
}

devBio[<span class="hljs-string">"age"</span>] = <span class="hljs-number">1</span>

print(devBio)

<span class="hljs-comment"># {'name': 'Chikara', 'age': 120, 'language': 'JavaScript'}</span>
</code></pre>
<p>In the example above, we reassigned a new value to <code>age</code>. This will override the initial value we assigned when the dictionary was created. </p>
<p>We can also use the <code>update()</code> method to change the value of items in our dictionary. We can achieve the same result in the last example by using the <code>update()</code> method – that is: <code>devBio.update({"age": 1})</code>. </p>
<h3 id="heading-items-in-a-dictionary-are-ordered">Items in a Dictionary Are Ordered</h3>
<p>By being ordered, this means that the items in a dictionary maintain the order in which they were created or added. That order cannot change. </p>
<p>Prior to Python 3.7, dictionaries in Python were unordered.</p>
<p>In the next section, we will see how we can add items to a dictionary.</p>
<h2 id="heading-how-to-add-an-item-to-a-dictionary">How to Add an Item to a Dictionary</h2>
<p>The syntax for adding items to a dictionary is the same as the syntax we used when updating an item. The only difference here is that the index key will include the name of the new key to be created and its corresponding value.</p>
<p>Here's what the syntax looks like: <code>devBio[**newKey**] = **newValue**</code><strong>.</strong></p>
<p>We can also use the <code>update()</code> method to add new items to a dictionary. Here's what that would look like: <code>devBio.**update**({"**newKey**": **newValue**})</code>. </p>
<p>Let's see some examples.</p>
<pre><code class="lang-python">devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">120</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"JavaScript"</span>
}

devBio[<span class="hljs-string">"role"</span>] = <span class="hljs-string">"Developer"</span>

print(devBio)

<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 120, 'language': 'JavaScript', 'role': 'Developer'}</span>
</code></pre>
<p>Above, using the index key <code>devBio["role"]</code>, we created a new key with the value of <code>Developer</code>.</p>
<p>In the next example, we will use the <code>update()</code> method. </p>
<pre><code class="lang-python">devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">120</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"JavaScript"</span>
}

devBio.update({<span class="hljs-string">"role"</span>: <span class="hljs-string">"Developer"</span>})

print(devBio)

<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 120, 'language': 'JavaScript', 'role': 'Developer'}</span>
</code></pre>
<p>Above, we achieved the same result as in the last example by passing in the new key and its value into the <code>update()</code> method – that is: <code>devBio.update({"role": "Developer"})</code>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we learned what dictionaries are in Python, how to create them, and some of their features. We then saw two ways through which we can add items to our dictionaries. </p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Create a Dictionary in Python – Python Dict Methods ]]>
                </title>
                <description>
                    <![CDATA[ In this article, you will learn the basics of dictionaries in Python. You will learn how to create dictionaries, access the elements inside them, and how to modify them depending on your needs. You will also learn some of the most common built-in met... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/create-a-dictionary-in-python-python-dict-methods/</link>
                <guid isPermaLink="false">66b1e3df0968943127cc5ef5</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Dionysia Lemonaki ]]>
                </dc:creator>
                <pubDate>Mon, 14 Mar 2022 14:19:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/03/pexels-kevin-ku-577585.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, you will learn the basics of dictionaries in Python.</p>
<p>You will learn how to create dictionaries, access the elements inside them, and how to modify them depending on your needs.</p>
<p>You will also learn some of the most common built-in methods used on dictionaries.</p>
<p>Here is what we will cover:</p>
<ol>
<li><a class="post-section-overview" href="#define-intro">Define a dictionary</a><ol>
<li><a class="post-section-overview" href="#define-empty">Define an empty dictionary</a></li>
<li><a class="post-section-overview" href="#define-items">Define a dictionary with items</a></li>
</ol>
</li>
<li><a class="post-section-overview" href="#overview">An overview of keys and values</a>
 1.<a class="post-section-overview" href="#length">Find the number of <code>key-value</code> pairs contained in a dictionary</a>
 2.<a class="post-section-overview" href="#key-value">View all <code>key-value</code> pairs</a>
 3.<a class="post-section-overview" href="#keys">View all <code>keys</code></a>
 4.<a class="post-section-overview" href="#values">View all <code>values</code></a></li>
<li><a class="post-section-overview" href="#access">Access individual items</a></li>
<li><a class="post-section-overview" href="#modify">Modify a dictionary</a><ol>
<li><a class="post-section-overview" href="#add">Add new items</a></li>
<li><a class="post-section-overview" href="#update">Update items</a></li>
<li><a class="post-section-overview" href="#delete">Delete items</a></li>
</ol>
</li>
</ol>
<h2 id="heading-how-to-create-a-dictionary-in-python">How to Create a Dictionary in Python <a></a></h2>
<p>A dictionary in Python is made up of key-value pairs.</p>
<p>In the two sections that follow you will see two ways of creating a dictionary. </p>
<p>The first way is by using a set of curly braces, <code>{}</code>, and the second way is by using the built-in <code>dict()</code> function.</p>
<h3 id="heading-how-to-create-an-empty-dictionary-in-python">How to Create An Empty Dictionary in Python <a></a></h3>
<p>To create an empty dictionary, first create a variable name which will be the name of the dictionary. </p>
<p>Then, assign the variable to an empty set of curly braces, <code>{}</code>.</p>
<pre><code class="lang-python"><span class="hljs-comment">#create an empty dictionary</span>
my_dictionary = {}

print(my_dictionary)

<span class="hljs-comment">#to check the data type use the type() function</span>
print(type(my_dictionary))

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{}</span>
<span class="hljs-comment">#&lt;class 'dict'&gt;</span>
</code></pre>
<p>Another way of creating an empty dictionary is to use the <code>dict()</code> function without passing any arguments.</p>
<p>It acts as a constructor and creates an empty dictionary:</p>
<pre><code class="lang-python"><span class="hljs-comment">#create an empty dictionary</span>
my_dictionary = dict()

print(my_dictionary)

<span class="hljs-comment">#to check the data type use the type() function</span>
print(type(my_dictionary))

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{}</span>
<span class="hljs-comment">#&lt;class 'dict'&gt;</span>
</code></pre>
<h3 id="heading-how-to-create-a-dictionary-with-items-in-python">How to Create A Dictionary With Items in Python <a></a></h3>
<p>To create a dictionary with items, you need to include <em>key-value</em> pairs inside the curly braces.</p>
<p>The general syntax for this is the following:</p>
<pre><code class="lang-python">dictionary_name = {key: value}
</code></pre>
<p>Let's break it down:</p>
<ul>
<li><code>dictionary_name</code> is the variable name. This is the name the dictionary will have.</li>
<li><code>=</code> is the assignment operator that assigns the <code>key:value</code> pair to the <code>dictionary_name</code>.</li>
<li>You declare a dictionary with a set of curly braces, <code>{}</code>.</li>
<li>Inside the curly braces you have a key-value pair. Keys are separated from their associated values with colon, <code>:</code>.</li>
</ul>
<p>Let's see an example of creating a dictionary with items:</p>
<pre><code class="lang-python"><span class="hljs-comment">#create a dictionary</span>
my_information = {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Dionysia'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">28</span>, <span class="hljs-string">'location'</span>: <span class="hljs-string">'Athens'</span>}

print(my_information)

<span class="hljs-comment">#check data type</span>
print(type(my_information))

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{'name': 'Dionysia', 'age': 28, 'location': 'Athens'}</span>
<span class="hljs-comment">#&lt;class 'dict'&gt;</span>
</code></pre>
<p>In the example above, there is a sequence of elements within the curly braces. </p>
<p>Specifically, there are three key-value pairs: <code>'name': 'Dionysia'</code>, <code>'age': 28</code>, and <code>'location': 'Athens'</code>.</p>
<p>The keys are <code>name</code>, <code>age</code>, and <code>location</code>. Their associated values are <code>Dionysia</code>, <code>28</code>, and <code>Athens</code>, respectively.</p>
<p>When there are multiple key-value pairs in a dictionary, each key-value pair is separated from the next with a comma, <code>,</code>.</p>
<p>Let's see another example.</p>
<p>Say that you want to create a dictionary with items using the <code>dict()</code> function this time instead.</p>
<p>You would achieve this by using <code>dict()</code> and passing the curly braces with the sequence of key-value pairs enclosed in them as an argument to the function.</p>
<pre><code class="lang-python"><span class="hljs-comment">#create a dictionary with dict()</span>
my_information = dict({<span class="hljs-string">'name'</span>: <span class="hljs-string">'Dionysia'</span> ,<span class="hljs-string">'age'</span>: <span class="hljs-number">28</span>,<span class="hljs-string">'location'</span>: <span class="hljs-string">'Athens'</span>})

print(my_information)

<span class="hljs-comment">#check data type</span>
print(type(my_information))

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{'name': 'Dionysia', 'age': 28, 'location': 'Athens'}</span>
<span class="hljs-comment">#&lt;class 'dict'&gt;</span>
</code></pre>
<p>It's worth mentioning the <code>fromkeys()</code> method, which is another way of creating a dictionary.</p>
<p>It takes a predefined sequence of items as an argument and returns a new dictionary with the items in the sequence set as the dictionary's specified keys.</p>
<p>You can <em>optionally</em> set a value for all the keys, but by default the value for the keys will be <code>None</code>.</p>
<p>The general syntax for the method is the following:</p>
<pre><code class="lang-python">dictionary_name = dict.fromkeys(sequence,value)
</code></pre>
<p>Let's see an example of creating a dictionary using <code>fromkeys()</code> without setting a value for all the keys:</p>
<pre><code class="lang-python"><span class="hljs-comment">#create sequence of strings</span>
cities = (<span class="hljs-string">'Paris'</span>,<span class="hljs-string">'Athens'</span>, <span class="hljs-string">'Madrid'</span>)

<span class="hljs-comment">#create the dictionary, `my_dictionary`, using the fromkeys() method</span>
my_dictionary = dict.fromkeys(cities)

print(my_dictionary)

<span class="hljs-comment">#{'Paris': None, 'Athens': None, 'Madrid': None}</span>
</code></pre>
<p>Now let's see another example that sets a value that will be the same for all the keys in the dictionary:</p>
<pre><code class="lang-python"><span class="hljs-comment">#create a sequence of strings</span>
cities = (<span class="hljs-string">'Paris'</span>,<span class="hljs-string">'Athens'</span>, <span class="hljs-string">'Madrid'</span>)

<span class="hljs-comment">#create a single value</span>
continent = <span class="hljs-string">'Europe'</span>

my_dictionary = dict.fromkeys(cities,continent)

print(my_dictionary)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{'Paris': 'Europe', 'Athens': 'Europe', 'Madrid': 'Europe'}</span>
</code></pre>
<h2 id="heading-an-overview-of-keys-and-values-in-dictionaries-in-python">An Overview of Keys and Values in Dictionaries in Python <a></a></h2>
<p>Keys inside a Python dictionary can <strong>only be of a type that is immutable</strong>.</p>
<p>Immutable data types in Python are <code>integers</code>, <code>strings</code>, <code>tuples</code>, <code>floating point numbers</code>, and <code>Booleans</code>.</p>
<p>Dictionary keys <strong>cannot</strong> be of a type that is mutable, such as <code>sets</code>, <code>lists</code>, or <code>dictionaries</code>.</p>
<p>So, say you have the following dictionary:</p>
<pre><code class="lang-python">my_dictionary = {<span class="hljs-literal">True</span>: <span class="hljs-string">"True"</span>,  <span class="hljs-number">1</span>: <span class="hljs-number">1</span>,  <span class="hljs-number">1.1</span>: <span class="hljs-number">1.1</span>, <span class="hljs-string">"one"</span>: <span class="hljs-number">1</span>, <span class="hljs-string">"languages"</span>: [<span class="hljs-string">"Python"</span>]}

print(my_dictionary)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{True: 1, 1.1: 1.1, 'one': 1, 'languages': ['Python']}</span>
</code></pre>
<p>The keys in the dictionary are  <code>Boolean</code>, <code>integer</code>, <code>floating point number</code>, and <code>string</code> data types, which are all acceptable.</p>
<p>If you try to create a key which is of a mutable type you'll get an error - specifically the error will be a <code>TypeError</code>.</p>
<pre><code class="lang-python">my_dictionary = {[<span class="hljs-string">"Python"</span>]: <span class="hljs-string">"languages"</span>}

print(my_dictionary)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#line 1, in &lt;module&gt;</span>
<span class="hljs-comment">#    my_dictionary = {["Python"]: "languages"}</span>
<span class="hljs-comment">#TypeError: unhashable type: 'list'</span>
</code></pre>
<p>In the example above, I tried to create a key which was of <code>list</code> type (a mutable data type). This resulted in a <code>TypeError: unhashable type: 'list'</code> error.</p>
<p>When it comes to values inside a Python dictionary there are no restrictions. Values can be of any data type - that is they can be both of mutable and immutable types.</p>
<p>Another thing to note about the differences between keys and values in Python dictionaries, is the fact that keys are <strong>unique</strong>. This means that a key can only appear once in the dictionary, whereas there can be duplicate values.</p>
<h3 id="heading-how-to-find-the-number-of-key-value-pairs-contained-in-a-dictionary-in-python">How to Find the Number of <code>key-value</code> Pairs Contained in a Dictionary in Python <a></a></h3>
<p>The <code>len()</code> function returns the total length of the object that is passed as an argument.</p>
<p>When a dictionary is passed as an argument to the function, it returns the total number of key-value pairs enclosed in the dictionary.</p>
<p>This is how you calcualte the number of key-value pairs using <code>len()</code>:</p>
<pre><code class="lang-python">my_information = {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Dionysia'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">28</span>, <span class="hljs-string">'location'</span>: <span class="hljs-string">'Athens'</span>}

print(len(my_information))

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#3</span>
</code></pre>
<h3 id="heading-how-to-view-all-key-value-pairs-contained-in-a-dictionary-in-python">How to View All <code>key-value</code> Pairs Contained in a Dictionary in Python <a></a></h3>
<p>To view every key-value pair that is inside a dictionary, use the built-in <code>items()</code> method:</p>
<pre><code class="lang-python">year_of_creation = {<span class="hljs-string">'Python'</span>: <span class="hljs-number">1993</span>, <span class="hljs-string">'JavaScript'</span>: <span class="hljs-number">1995</span>, <span class="hljs-string">'HTML'</span>: <span class="hljs-number">1993</span>}

print(year_of_creation.items())

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#dict_items([('Python', 1993), ('JavaScript', 1995), ('HTML', 1993)])</span>
</code></pre>
<p>The <code>items()</code> method returns a list of tuples that contains the key-value pairs that are inside the dictionary.</p>
<h3 id="heading-how-to-view-all-keys-contained-in-a-dictionary-in-python">How to View All <code>keys</code> Contained in a Dictionary in Python <a></a></h3>
<p>To see all of the keys that are inside a dictionary, use the built-in <code>keys()</code> method:</p>
<pre><code class="lang-python">year_of_creation = {<span class="hljs-string">'Python'</span>: <span class="hljs-number">1993</span>, <span class="hljs-string">'JavaScript'</span>: <span class="hljs-number">1995</span>, <span class="hljs-string">'HTML'</span>: <span class="hljs-number">1993</span>}

print(year_of_creation.keys())

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#dict_keys(['Python', 'JavaScript', 'HTML'])</span>
</code></pre>
<p>The <code>keys()</code> method returns a list that contains only the keys that are inside the dictionary.</p>
<h3 id="heading-how-to-view-all-values-contained-in-a-dictionary-in-python">How to View All <code>values</code> Contained in a Dictionary in Python <a></a></h3>
<p>To see all of the values that are inside a dictionary, use the built-in <code>values()</code> method:</p>
<pre><code class="lang-python">year_of_creation = {<span class="hljs-string">'Python'</span>: <span class="hljs-number">1993</span>, <span class="hljs-string">'JavaScript'</span>: <span class="hljs-number">1995</span>, <span class="hljs-string">'HTML'</span>: <span class="hljs-number">1993</span>}

print(year_of_creation.values())

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#dict_values([1993, 1995, 1993])</span>
</code></pre>
<p>The <code>values()</code> method returns a list that contains only the values that are inside the dictionary.</p>
<h2 id="heading-how-to-access-individual-items-in-a-dictionary-in-python">How to Access Individual Items in A Dictionary in Python <a></a></h2>
<p>When working with lists, you access list items by mentioning the list name and using square bracket notation. In the square brackets you specify the item's index number (or position).</p>
<p>You can't do exactly the same with dictionaries.</p>
<p>When working with dictionaries, you can't access an element by referencing its index number, since dictionaries contain key-value pairs.</p>
<p>Instead, you access the item by using the dictionary name and square bracket notation, but this time in the square brackets you specify a key.</p>
<p>Each key corresponds with a specific value, so you mention the key that is  associated with the value you want to access.</p>
<p>The general syntax to do so is the following:</p>
<pre><code class="lang-python">dictionary_name[key]
</code></pre>
<p>Let's look at the following example on how to access an item in a Python dictionary:</p>
<pre><code class="lang-python">my_information = {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Dionysia'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">28</span>, <span class="hljs-string">'location'</span>: <span class="hljs-string">'Athens'</span>}

<span class="hljs-comment">#access the value associated with the 'age' key</span>
print(my_information[<span class="hljs-string">'age'</span>])

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#28</span>
</code></pre>
<p>What happens though when you try to access a key that doesn't exist in the dictionary?</p>
<pre><code class="lang-python">my_information = {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Dionysia'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">28</span>, <span class="hljs-string">'location'</span>: <span class="hljs-string">'Athens'</span>}

<span class="hljs-comment">#try to access the value associated with the 'job' key</span>
print(my_information[<span class="hljs-string">'job'</span>])

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#line 4, in &lt;module&gt;</span>
<span class="hljs-comment">#    print(my_information['job'])</span>
<span class="hljs-comment">#KeyError: 'job'</span>
</code></pre>
<p>It results in a <code>KeyError</code> since there is no such key in the dictionary.</p>
<p>One way to avoid this from happening is to first search to see if the key is in the dictionary in the first place.</p>
<p>You do this by using the <code>in</code> keyword which returns a Boolean value. It returns <code>True</code> if the key is in the dictionary and <code>False</code> if it isn't.</p>
<pre><code class="lang-python">my_information = {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Dionysia'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">28</span>, <span class="hljs-string">'location'</span>: <span class="hljs-string">'Athens'</span>}

<span class="hljs-comment">#search for the 'job' key</span>
print(<span class="hljs-string">'job'</span> <span class="hljs-keyword">in</span> my_information)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#False</span>
</code></pre>
<p>Another way around this is to access items in the dictionary by using the <code>get()</code> method. </p>
<p>You pass the key you're looking for as an argument and <code>get()</code> returns the value that corresponds with that key.</p>
<pre><code class="lang-python">my_information = {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Dionysia'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">28</span>, <span class="hljs-string">'location'</span>: <span class="hljs-string">'Athens'</span>}

<span class="hljs-comment">#try to access the 'job' key using the get() method</span>
print(my_information.get(<span class="hljs-string">'job'</span>))

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#None</span>
</code></pre>
<p>As you notice, when you are searching for a key that does not exist, by default <code>get()</code> returns <code>None</code> instead of a <code>KeyError</code>.</p>
<p>If instead of showing that default <code>None</code> value you want to show a different message when a key does not exist, you can customise <code>get()</code> by providing a different value.</p>
<p>You do so by passing the new value as the second optional argument to the <code>get()</code> method:</p>
<pre><code class="lang-python">my_information = {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Dionysia'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">28</span>, <span class="hljs-string">'location'</span>: <span class="hljs-string">'Athens'</span>}

<span class="hljs-comment">#try to access the 'job' key using the get() method</span>
print(my_information.get(<span class="hljs-string">'job'</span>, <span class="hljs-string">'This value does not exist'</span>))

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#This value does not exist</span>
</code></pre>
<p>Now when you are searching for a key and it is not contained in the dictionary, you will see the message <code>This value does not exist</code> appear on the console.</p>
<h2 id="heading-how-to-modify-a-dictionary-in-python">How to Modify A Dictionary in Python <a></a></h2>
<p>Dictionaries are <em>mutable</em>, which means they are changeable.</p>
<p>They can grow and shrink throughout the life of the program.</p>
<p>New items can be added, already existing items can be updated with new values, and items can be deleted.</p>
<h3 id="heading-how-to-add-new-items-to-a-dictionary-in-python">How to Add New Items to A Dictionary in Python <a></a></h3>
<p>To add a key-value pair to a dictionary, use square bracket notation.</p>
<p>The general syntax to do so is the following:</p>
<pre><code class="lang-python">dictionary_name[key] = value
</code></pre>
<p>First, specify the name of the dictionary. Then, in square brackets, create a key and assign it a value.</p>
<p>Say you are starting out with an empty dictionary:</p>
<pre><code class="lang-python">my_dictionary = {}

print(my_dictionary)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{}</span>
</code></pre>
<p>Here is how you would add a key-value pair to <code>my_dictionary</code>:</p>
<pre><code class="lang-python">my_dictionary = {}

<span class="hljs-comment">#add a key-value pair to the empty dictionary</span>
my_dictionary[<span class="hljs-string">'name'</span>] = <span class="hljs-string">"John Doe"</span>

<span class="hljs-comment">#print dictionary</span>
print(my_list)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{'name': 'John Doe'}</span>
</code></pre>
<p>Here is how you would add another new key-value pair:</p>
<pre><code class="lang-python">my_dictionary = {}

<span class="hljs-comment">#add a key-value pair to the empty dictionary</span>
my_dictionary[<span class="hljs-string">'name'</span>] = <span class="hljs-string">"John Doe"</span>

<span class="hljs-comment"># add another  key-value pair</span>
my_dictionary[<span class="hljs-string">'age'</span>] = <span class="hljs-number">34</span>

<span class="hljs-comment">#print dictionary</span>
print(my_dictionary)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{'name': 'John Doe', 'age': 34}</span>
</code></pre>
<p>Keep in mind that if the key you are trying to add already exists in that dictionary and you are assigning it a different value, the key will end up being updated.</p>
<p>Remember that keys need to be unique.</p>
<pre><code class="lang-python">my_dictionary = {<span class="hljs-string">'name'</span>: <span class="hljs-string">"John Doe"</span>, <span class="hljs-string">'age'</span>:<span class="hljs-number">34</span>}

print(my_dictionary)

<span class="hljs-comment">#try to create a an 'age' key and assign it a value</span>
<span class="hljs-comment">#the 'age' key already exists</span>

my_dictionary[<span class="hljs-string">'age'</span>] = <span class="hljs-number">46</span>

<span class="hljs-comment">#the value of 'age' will now be updated</span>

print(my_dictionary)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{'name': 'John Doe', 'age': 34}</span>
<span class="hljs-comment">#{'name': 'John Doe', 'age': 46}</span>
</code></pre>
<p>If you want to prevent changing the value of an already existing key by accident, you might want to check if the key you are trying to add is already in the dictionary.</p>
<p>You do this by using the <code>in</code> keyword as we discussed above:</p>
<pre><code class="lang-python">my_dictionary = {<span class="hljs-string">'name'</span>: <span class="hljs-string">"John Doe"</span>, <span class="hljs-string">'age'</span>:<span class="hljs-number">34</span>}

<span class="hljs-comment">#I want to add an `age` key. Before I do so, I check to see if it already exists</span>
print(<span class="hljs-string">'age'</span> <span class="hljs-keyword">in</span> my_dictionary)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#True</span>
</code></pre>
<h3 id="heading-how-to-update-items-in-a-dictionary-in-python">How to Update Items in A Dictionary in Python <a></a></h3>
<p>Updating items in a dictionary works in a similar way to adding items to a dictionary.</p>
<p>When you know you want to update one existing key's value, use the following general syntax you saw in the previous section:</p>
<pre><code class="lang-python">dictionary_name[existing_key] = new_value
</code></pre>
<pre><code class="lang-python">my_dictionary = {<span class="hljs-string">'name'</span>: <span class="hljs-string">"John Doe"</span>, <span class="hljs-string">'age'</span>:<span class="hljs-number">34</span>}

my_dictionary[<span class="hljs-string">'age'</span>] = <span class="hljs-number">46</span>

print(my_dictionary)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{'name': 'John Doe', 'age': 46}</span>
</code></pre>
<p>To update a dictionary, you can also use the built-in <code>update()</code> method.</p>
<p>This method is particularly helpful when you want to update more than one value inside a dictionary at the same time.</p>
<p>Say you want to update the <code>name</code> and <code>age</code> key in <code>my_dictionary</code>, and add a new key, <code>occupation</code>:</p>
<pre><code class="lang-python">my_dictionary = {<span class="hljs-string">'name'</span>: <span class="hljs-string">"John Doe"</span>, <span class="hljs-string">'age'</span>:<span class="hljs-number">34</span>}

my_dictionary.update(name= <span class="hljs-string">'Mike Green'</span>, age = <span class="hljs-number">46</span>, occupation = <span class="hljs-string">"software developer"</span>)

print(my_dictionary)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{'name': 'Mike Green', 'age': 46, 'occupation': 'software developer'}</span>
</code></pre>
<p>The <code>update()</code> method takes a tuple of key-value pairs.</p>
<p>The keys that already existed were updated with the new values that were assigned, and a new key-value pair was added.</p>
<p>The <code>update()</code> method is also useful when you want to add the contents of one dictionary into another.</p>
<p>Say you have one dictionary, <code>numbers</code>, and a second dictionary, <code>more_numbers</code>.</p>
<p>If you want to merge the contents of <code>more_numbers</code> with the contents of <code>numbers</code>, use the <code>update()</code> method. </p>
<p>All the key-value pairs contained in <code>more_numbers</code> will be added to the end of the <code>numbers</code> dictionary.</p>
<pre><code class="lang-python">numbers = {<span class="hljs-string">'one'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'two'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'three'</span>: <span class="hljs-number">3</span>}
more_numbers = {<span class="hljs-string">'four'</span>: <span class="hljs-number">4</span>, <span class="hljs-string">'five'</span>: <span class="hljs-number">5</span>, <span class="hljs-string">'six'</span>: <span class="hljs-number">6</span>}

<span class="hljs-comment">#update 'numbers' dictionary</span>
<span class="hljs-comment">#you update it by adding the contents of another dictionary, 'more_numbers',</span>
<span class="hljs-comment">#to the end of it</span>
numbers.update(more_numbers)

print(numbers)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}</span>
</code></pre>
<h3 id="heading-how-to-delete-items-from-a-dictionary-in-python">How to Delete Items from A Dictionary in Python <a></a></h3>
<p>One of the ways to delete a specific key and its associated value from a dictionary is by using the <code>del</code> keyword.</p>
<p>The syntax to do so is the following:</p>
<pre><code class="lang-python"><span class="hljs-keyword">del</span> dictionary_name[key]
</code></pre>
<p>For example, this is how you would delete the <code>location</code> key from the <code>my_information</code> dictionary:</p>
<pre><code class="lang-python">my_information = {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Dionysia'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">28</span>, <span class="hljs-string">'location'</span>: <span class="hljs-string">'Athens'</span>}

<span class="hljs-keyword">del</span> my_information[<span class="hljs-string">'location'</span>]

print(my_information)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{'name': 'Dionysia', 'age': 28}</span>
</code></pre>
<p>If you want to remove a key, but would also like to save that removed value, use the built-in <code>pop()</code> method.</p>
<p>The <code>pop()</code> method removes but also returns the key you specify. This way, you can store the removed value in a variable for later use or retrieval.</p>
<p>You pass the key you want to remove as an argument to the method.</p>
<p>Here is the general syntax to do that:</p>
<pre><code class="lang-python">dictionary_name.pop(key)
</code></pre>
<p>To remove the <code>location</code> key from the example above, but this time using the <code>pop()</code> method and saving the value associated with the key to a variable, do the following:</p>
<pre><code class="lang-python">my_information = {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Dionysia'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">28</span>, <span class="hljs-string">'location'</span>: <span class="hljs-string">'Athens'</span>}

city = my_information.pop(<span class="hljs-string">'location'</span>)

print(my_information)
print(city)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{'name': 'Dionysia', 'age': 28}</span>
<span class="hljs-comment">#Athens</span>
</code></pre>
<p>If you specify a key that does not exist in the dictionary you will get a <code>KeyError</code> error message:</p>
<pre><code class="lang-python">my_information = {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Dionysia'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">28</span>, <span class="hljs-string">'location'</span>: <span class="hljs-string">'Athens'</span>}

my_information.pop(<span class="hljs-string">'occupation'</span>)

print(my_information)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#line 3, in &lt;module&gt;</span>
<span class="hljs-comment">#   my_information.pop('occupation')</span>
<span class="hljs-comment">#KeyError: 'occupation'</span>
</code></pre>
<p>A way around this is to pass a second argument to the <code>pop()</code> method. </p>
<p>By including the second argument there would be no error. Instead, there would be a silent fail if the key didn't exist, and the dictionary would remain unchanged.</p>
<pre><code class="lang-python">my_information = {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Dionysia'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">28</span>, <span class="hljs-string">'location'</span>: <span class="hljs-string">'Athens'</span>}

my_information.pop(<span class="hljs-string">'occupation'</span>,<span class="hljs-string">'Not found'</span>)

print(my_information)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{'name': 'Dionysia', 'age': 28, 'location': 'Athens'}</span>
</code></pre>
<p>The <code>pop()</code> method removes a specific key and its associated value – but what if you only want to delete the <strong>last</strong> key-value pair from a dictionary?</p>
<p>For that, use the built-in <code>popitem()</code> method instead.</p>
<p>This is general syntax for the <code>popitem()</code> method:</p>
<pre><code class="lang-python">dictionary_name.popitem()
</code></pre>
<p>The <code>popitem()</code> method takes no arguments, but removes and returns the last key-value pair from a dictionary.</p>
<pre><code class="lang-python">my_information = {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Dionysia'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">28</span>, <span class="hljs-string">'location'</span>: <span class="hljs-string">'Athens'</span>}

popped_item = my_information.popitem()

print(my_information)
print(popped_item)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{'name': 'Dionysia', 'age': 28}</span>
<span class="hljs-comment">#('location', 'Athens')</span>
</code></pre>
<p>Lastly, if you want to delete all key-value pairs from a dictionary, use the built-in <code>clear()</code> method.</p>
<pre><code class="lang-python">my_information = {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Dionysia'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">28</span>, <span class="hljs-string">'location'</span>: <span class="hljs-string">'Athens'</span>}

my_information.clear()

print(my_information)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#{}</span>
</code></pre>
<p>Using this method will leave you with an empty dictionary.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>And there you have it! You now know the basics of dictionaries in Python.</p>
<p>I hope you found this article useful.</p>
<p>To learn more about the Python programming language, check out freeCodeCamp's <a target="_blank" href="https://www.freecodecamp.org/learn/scientific-computing-with-python/">Scientific Computing with Python Certification</a>.</p>
<p>You'll start from the basics and learn in an interacitve and beginner-friendly way. You'll also build five projects at the end to put into practice and help reinforce what you've learned.</p>
<p>Thanks for reading and happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
