<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python 3 Archives - Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/tag/python-3/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/tag/python-3/</link>
	<description></description>
	<lastBuildDate>Sat, 11 Nov 2023 13:25:32 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>Python 3 Archives - Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/tag/python-3/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>A Recursive Pathfinder Algorithm in Python</title>
		<link>https://blog.finxter.com/recursive-pathfinder-algorithm-python/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Mon, 15 Feb 2021 22:10:00 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Graph Theory]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Adjacency Matrix]]></category>
		<category><![CDATA[Graph]]></category>
		<category><![CDATA[Path]]></category>
		<category><![CDATA[Pathfinder]]></category>
		<category><![CDATA[Python 3]]></category>
		<category><![CDATA[Recursion]]></category>
		<category><![CDATA[Recursive]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=491</guid>

					<description><![CDATA[<p>A simple and effective way to grow your computer science skills is to master the basics. Knowing the basics sets apart the great coders from the merely intermediate ones. One such basic area in computer science is graph theory, a specific subproblem of which&#8212;the pathfinder algorithm&#8212;we&#8217;ll address in this tutorial. So first things first: What ... <a title="A Recursive Pathfinder Algorithm in Python" class="read-more" href="https://blog.finxter.com/recursive-pathfinder-algorithm-python/" aria-label="Read more about A Recursive Pathfinder Algorithm in Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/recursive-pathfinder-algorithm-python/">A Recursive Pathfinder Algorithm in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>A simple and effective way to grow your computer science skills is to master the basics. Knowing the basics sets apart the great coders from the merely intermediate ones. </p>



<p>One such basic area in computer science is <strong><em><a href="https://blog.finxter.com/graph-applications/" title="What are the Applications of Graphs in Computer Science?" target="_blank" rel="noreferrer noopener">graph theory</a></em></strong>, a specific subproblem of which&#8212;the pathfinder algorithm&#8212;we&#8217;ll address in this tutorial. So first things first: </p>



<h2 class="wp-block-heading">What Is a Graph?</h2>



<p>You may already know data structures like <a href="https://blog.finxter.com/python-lists/" title="The Ultimate Guide to Python Lists" target="_blank" rel="noreferrer noopener">lists</a>, <a href="https://blog.finxter.com/sets-in-python/" title="The Ultimate Guide to Python Sets – with Harry Potter Examples" target="_blank" rel="noreferrer noopener">sets</a>, and <a href="https://blog.finxter.com/python-dictionary/" title="Python Dictionary – The Ultimate Guide" target="_blank" rel="noreferrer noopener">dictionaries</a>. These data structures are denoted as complex data structures&#8211;not because they&#8217;re difficult to understand but because they build upon other data structures.</p>



<p>A graph is just another complex data structure for relational data.</p>



<p>Relational data consists of edges and vertices. Each vertex stands in one or more relations with other vertices. </p>



<p>An example of relational data is the Facebook social graph. Facebook represents users as vertices and friendship relations as edges. Two users are connected via an edge in the graph if they are (Facebook) friends.</p>



<p class="has-cyan-bluish-gray-background-color has-background"><strong>What is a graph?</strong> A graph is a basic data structure in computer science. It models relationships between data items. Using graphs to model real-world phenomena is not a new idea. In 1736, Leonhard Euler has invented the graph data structure to solve the problem of <a href="https://en.wikipedia.org/wiki/Seven_Bridges_of_K%C3%B6nigsberg">“seven bridges of Königsberg”</a>. Graphs existed way before the first computer was even an idea. In fact, as we will see in this article, graphs helped to make the computer possible. Without graphs, there wouldn’t be a computer as we now know it today.</p>



<h2 class="wp-block-heading">How to Represent a Graph Data Structure in the Code? </h2>



<p>In this tutorial, we&#8217;ll use an <a rel="noreferrer noopener" title="https://en.wikipedia.org/wiki/Adjacency_matrix" href="https://en.wikipedia.org/wiki/Adjacency_matrix" target="_blank">adjacency matrix</a> as a graph data structure <code>G</code>. </p>



<p>Each row <code>i</code> in the matrix stores the out-neighbors of vertex <code>i</code>. And each column <code>j</code> stores the in-neighbors of vertex <code>j</code>. </p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Thus, there is an edge from vertex <code>i</code> to vertex <code>j</code>, if <code>G[i][j]==1</code>.</p>



<p>You can see an example of the adjacency matrix graph representation in the following code of the Pathfinder algorithm:</p>



<h2 class="wp-block-heading">The Pathfinder Algorithm in Python</h2>



<p>How to determine whether there is a path between two vertices? </p>



<p>The function <code>find_path(graph, v_start, v_end, path_len)</code> checks whether there is a direct or indirect path between two vertices <code>v_start</code> and <code>v_end</code> in graph. We know that there is a direct path between <code>v_start</code> and <code>v_end</code> if both are already neighbors, i.e., <code>graph[v_start][v_end]==1</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def find_path(graph, v_start, v_end, path_len=0):
    '''Is there a path between vertex v_start and vertex v_end?'''

    # Traverse each vertex only once
    if path_len >= len(graph):
        return False

    # Direct path from v_start to v_end?
    if graph[v_start][v_end]:
        return True

    # Indirect path via neighbor v_nbor?
    for v_nbor, edge in enumerate(graph[v_start]):
        if edge:
            # between v_start and v_nbor
            if find_path(graph, v_nbor, v_end, path_len + 1):
                return True

    # No direct or indirect path found
    return False

# The graph represented as adjancy matrix
G = [[1, 1, 0, 0, 0],
     [0, 1, 0, 0, 0],
     [0, 0, 1, 0, 0],
     [0, 1, 1, 1, 0],
     [1, 0, 0, 1, 1]]

print(find_path(graph=G, v_start=3, v_end=0))
# False

print(find_path(G, 3, 1))
# True
</pre>



<p>However, even if there is not a direct path, there could be an indirect path between vertices <code>v_start</code> and <code>v_end</code>. </p>



<p>To check this, the algorithm uses a recursive approach. Specifically, there is an indirect path if a vertex <code>v_nbor</code> exists such that there is a path:</p>



<pre class="wp-block-preformatted"><code> v_start --> v_nbor --> ... --> v_end</code></pre>



<p>The variable <code>path_len</code> stores the length of the current path. </p>



<p>We increment it in each recursion level as the current path length increases by one. Note that all paths with length <code>>=n</code> consist of at least <code>n</code> vertices. </p>



<p>In other words, at least one vertex is visited twice and a cycle exists in this recursion instance. Hence, we skip recursion for paths with lengths greater than or equal to the number of vertices in the graph.</p>



<p>In the code snippet, we check whether there is a path between 3 and 0. </p>



<p>If you understand what the code is doing, it suffices to look at the adjacency matrix <code>G</code>. </p>



<p>There is a direct path from vertex 3 to vertices 1 and 2 (and to itself). But neither vertex 1 nor 2 has any out-neighbors. </p>



<p>Therefore, there is no path from vertex 3 to any other vertex (besides vertices 1 and 2).</p>



<h2 class="wp-block-heading">Related Video</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="Graph Theory Overview" width="937" height="527" src="https://www.youtube.com/embed/82zlRaRUsaY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>






<h2 class="wp-block-heading">Academy Course &#8211; Mastering the Top 10 Graph Algorithms</h2>



<p>If you want to improve your fundamental computer science skills, there&#8217;s nothing more effective than <strong>studying algorithms</strong>. </p>



<p>To help you master the <strong>most important graph algorithms</strong>, we&#8217;ve just launched the &#8220;Top 10 Algorithms&#8221; course at the <a rel="noreferrer noopener" href="https://academy.finxter.com/university/graph-algorithms-in-python/" data-type="URL" data-id="https://academy.finxter.com/university/graph-algorithms-in-python/" target="_blank">Finxter Computer Science Academy</a>. This great course from Finxter Star Creator Matija <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2b50.png" alt="⭐" class="wp-smiley" style="height: 1em; max-height: 1em;" /> teaches you the most important graph algorithms such as BFS, DFS, A*, and Dijkstra. </p>



<p>Understanding these algorithms will not only make you a better coder, but it&#8217;ll also lay a strong foundation on which you can build your whole career as a computer scientist.</p>



<p>Click the screenshot to find out more:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><a href="https://academy.finxter.com/university/graph-algorithms-in-python/" target="_blank" rel="noopener"><img fetchpriority="high" decoding="async" width="363" height="650" src="https://blog.finxter.com/wp-content/uploads/2022/03/image-141.png" alt="" class="wp-image-246565" srcset="https://blog.finxter.com/wp-content/uploads/2022/03/image-141.png 363w, https://blog.finxter.com/wp-content/uploads/2022/03/image-141-168x300.png 168w" sizes="(max-width: 363px) 100vw, 363px" /></a></figure></div>



<div class="wp-block-buttons alignwide is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button has-custom-width wp-block-button__width-50"><a class="wp-block-button__link" href="https://academy.finxter.com/university/graph-algorithms-in-python/" target="_blank" rel="noreferrer noopener">Learn More</a></div>
</div>



<p></p>
<p>The post <a href="https://blog.finxter.com/recursive-pathfinder-algorithm-python/">A Recursive Pathfinder Algorithm in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Calculate the Weighted Average of a Numpy Array in Python?</title>
		<link>https://blog.finxter.com/how-to-calculate-weighted-average-numpy-array-along-axis/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sun, 14 Feb 2021 12:13:00 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[2D array]]></category>
		<category><![CDATA[Average]]></category>
		<category><![CDATA[axis]]></category>
		<category><![CDATA[numpy]]></category>
		<category><![CDATA[Numpy Array]]></category>
		<category><![CDATA[Python 3]]></category>
		<category><![CDATA[weight]]></category>
		<category><![CDATA[weighted average]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=477</guid>

					<description><![CDATA[<p>Problem Formulation: How to calculate the weighted average of the elements in a NumPy array? Definition weighted average: Each array element has an associated weight. The weighted average is the sum of all array elements, properly weighted, divided by the sum of all weights. Here&#8217;s the problem exemplified: Quick solution: Before we discuss the solution ... <a title="How to Calculate the Weighted Average of a Numpy Array in Python?" class="read-more" href="https://blog.finxter.com/how-to-calculate-weighted-average-numpy-array-along-axis/" aria-label="Read more about How to Calculate the Weighted Average of a Numpy Array in Python?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-calculate-weighted-average-numpy-array-along-axis/">How to Calculate the Weighted Average of a Numpy Array in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p><strong>Problem Formulation:</strong> How to calculate the weighted average of the elements in a NumPy array?</p>



<p><strong>Definition weighted average: </strong>Each array element has an associated weight. The weighted average is the sum of all array elements, properly weighted, divided by the sum of all weights.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" width="705" height="115" src="https://blog.finxter.com/wp-content/uploads/2021/02/image-61.png" alt="" class="wp-image-23953" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/image-61.png 705w, https://blog.finxter.com/wp-content/uploads/2021/02/image-61-300x49.png 300w" sizes="(max-width: 705px) 100vw, 705px" /></figure>
</div>


<p>Here&#8217;s the problem exemplified:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2021/02/weighted_average_problem-1024x576.jpg" alt="Weighted Average of NumPy Array - Problem Example" class="wp-image-23956" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/weighted_average_problem-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2021/02/weighted_average_problem-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2021/02/weighted_average_problem-768x432.jpg 768w" sizes="auto, (max-width: 768px) 100vw, 768px" /></figure>
</div>


<p><strong>Quick solution:</strong> Before we discuss the solution in great detail, here&#8217;s the solution that solves this exact problem:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np

array = np.array([[1, 0, 2],
                  [1, 1, 1]])
weights = np.array([[2, 1, 1],
                    [1, 1, 2]])

print(np.average(array, weights=weights))
# 1.0</pre>



<p>Want to learn how it works&#8212;and how you can average along an axis as well? Let&#8217;s dive deeper into the problem next!</p>



<h2 class="wp-block-heading">Weighted Average with NumPy&#8217;s np.average() Function</h2>



<p>NumPy&#8217;s <code><a href="https://blog.finxter.com/numpy-average/" title="NumPy Average">np.average(arr)</a></code> function computes the average of all numerical values in a NumPy array. When used with only one array argument, it calculates the numerical average of all values in the array, no matter the array&#8217;s dimensionality. For example, the expression <code>np.average([[1,2],[2,3]])</code> results in the average value <code>(1+2+2+3)/4 = 2.0</code>.</p>



<p>However, what if you want to calculate the <strong>weighted average</strong> of a NumPy array? In other words, you want to <em>overweigh</em>t some array values and <em>underweigh</em>t others.</p>



<p>You can easily accomplish this with NumPy&#8217;s <a href="https://blog.finxter.com/how-to-average-a-list-of-lists-in-python/" target="_blank" rel="noreferrer noopener">average </a>function by passing the weights argument to the NumPy <code><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.average.html" target="_blank" rel="noreferrer noopener" title="https://docs.scipy.org/doc/numpy/reference/generated/numpy.average.html">average</a></code> function. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np

a = [-1, 1, 2, 2]

print(np.average(a))
# 1.0

print(np.average(a, weights = [1, 1, 1, 5]))
# 1.5</pre>



<p>In the first example, we simply averaged over all array values: <code>(-1+1+2+2)/4 = 1.0</code>. However, in the second example, we overweight the last array element 2&#8212;it now carries five times the weight of the other elements resulting in the following computation: <code>(-1+1+2+(2+2+2+2+2))/8 = 1.5</code>.</p>



<h2 class="wp-block-heading">NumPy Weighted Average Video</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Calculate the Weighted Average of a Numpy Array in Python?" width="937" height="527" src="https://www.youtube.com/embed/b0U31GkE7ho?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">NumPy Average Syntax</h2>



<p>Let&#8217;s explore the different parameters we can pass to <code>np.average(...)</code>.</p>



<ul class="wp-block-list">
<li><strong>The NumPy array</strong> which can be multi-dimensional.</li>



<li>(Optional) <strong>The axis</strong> along which you want to average. If you don&#8217;t specify the argument, the averaging is done over the whole array.</li>



<li>(Optional) <strong>The weights</strong> of each column of the specified axis. If you don&#8217;t specify the argument, the weights are assumed to be homogeneous.</li>



<li>(Optional) <strong>The return value</strong> of the function. Only if you set this to True, you will get a tuple (average, weights_sum) as a result. This may help you to normalize the output. In most cases, you can skip this argument.</li>
</ul>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">average(a, axis=None, weights=None, returned=False)</pre>



<figure class="wp-block-table is-style-stripes"><table><thead><tr><th>Argument</th><th>Description</th></tr></thead><tbody><tr><td><code>a</code></td><td><em><strong>array-like</strong></em>: The array contains the data to be averaged. Can be multi-dimensional and it doesn’t have to be a NumPy array—but usually, it is.</td></tr><tr><td><code>axis=None</code></td><td><strong><em>None or int or tuple of ints:</em></strong> The axis along which to average the array <code>a</code>.</td></tr><tr><td><code>weights=None</code></td><td><em><strong>array-like</strong></em>: An array of weights associated to the values in the array <code>a</code>. This allows you to customize the weight towards the average of each element in the array.</td></tr><tr><td><code>returned=False</code></td><td><strong><em>Boolean</em></strong>: If <code>False</code>, returns the average value. If <code>True</code>, returns the tuple of the <code>(average, sum_of_weights)</code> so that you can easily normalize the weighted average.</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">NumPy Weighted Average Along an Axis (Puzzle)</h2>



<p>Here is an example how to <a href="https://blog.finxter.com/numpy-average-along-axis/" target="_blank" rel="noreferrer noopener">average along the columns</a> of a 2D NumPy array with specified weights for both rows.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np

# daily stock prices
# [morning, midday, evening]
solar_x = np.array(
    [[2, 3, 4], # today
     [2, 2, 5]]) # yesterday

# midday - weighted average
print(np.average(solar_x, axis=0, weights=[3/4, 1/4])[1])</pre>



<p><em>What is the output of this puzzle?</em><br>*Beginner Level* (solution below)</p>



<p>You can also solve this puzzle in our puzzle-based learning app (100% FREE):<a href="https://app.finxter.com/learn/computer/science/433" target="_blank" rel="noreferrer noopener">&nbsp;Test your skills now!</a></p>



<h2 class="wp-block-heading">Puzzle Explanation</h2>



<p>Numpy is a popular Python library for data science focusing on arrays, vectors, and matrices.</p>



<p>This puzzle introduces the average function from the NumPy library. When applied to a 1D NumPy array, this function returns the average of the array values. When applied to a 2D NumPy array, it simply flattens the array. The result is the average of the flattened 1D array.</p>



<p>In the puzzle, we have a matrix with two rows and three columns. The matrix gives the stock prices of the <code>solar_x</code> stock. Each row represents the prices for one day. The first column specifies the morning price, the second the midday price, and the third the evening price.</p>



<p>Now suppose, we do not want to know the <a href="https://blog.finxter.com/how-to-calculate-simple-average-of-numpy-array/" target="_blank" rel="noreferrer noopener" title="How to Calculate the Average of a NumPy 2D Array?">average of the flattened matrix</a> but the average of the price in the midday. Moreover, we want to overweight the most recent stock price. Today accounts for three-quarters and yesterday for one-quarter of the final average value.</p>



<p><a href="https://blog.finxter.com/numpy-tutorial/" title="NumPy Tutorial – Everything You Need to Know to Get Started" target="_blank" rel="noreferrer noopener">NumPy </a>enables this via the <code>weights</code> parameter in combination with the <code>axis</code> parameter.</p>



<ul class="wp-block-list">
<li>The <code>weights</code> parameter defines the weight for each value participating in the average calculation. </li>



<li>The <code>axis</code> parameter specifies the direction along which the average should be calculated.</li>
</ul>



<p>In a 2D matrix, the row is specified as <code>axis=0</code> and the column as <code>axis=1</code>. We want to know three average values, for the morning, midday, and evening. We calculate the average along the row, i.e., <code>axis=0</code>. This results in three average values. Now we take the second element to get the midday variance.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/how-to-normalize-a-numpy-matrix/" data-type="post" data-id="1045844" target="_blank" rel="noreferrer noopener">How to Normalize a NumPy Matrix</a></p>



<h2 class="wp-block-heading">Where to Go From Here?</h2>



<p>Want to thrive in data science? Master NumPy first. You need to know the most important concepts (such as the axis argument) before you dive into machine learning and data science. Only then, you can properly understand the algorithms and build your career on a solid foundation. </p>



<p>To help you accomplish this, we&#8217;ve written an easy-to-read, fun introduction into the NumPy library. It&#8217;s 100% based on puzzle-based learning: you solve rated NumPy puzzles, test your skills, and improve over time. Check it out&#8212;it&#8217;s fun! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<figure class="wp-block-image is-resized"><a href="https://blog.finxter.com/coffee-break-numpy/" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2019/04/Cover_Coffee_Break_NumPy_v2-683x1024.png" alt="" class="wp-image-2792" width="342" height="512"/></a></figure>



<h4 class="wp-block-heading">Solution</h4>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>2.75</p>
</blockquote>
<p>The post <a href="https://blog.finxter.com/how-to-calculate-weighted-average-numpy-array-along-axis/">How to Calculate the Weighted Average of a Numpy Array in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Calculate the Average of a NumPy 2D Array?</title>
		<link>https://blog.finxter.com/how-to-calculate-simple-average-of-numpy-array/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 13 Feb 2021 07:42:00 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[2D array]]></category>
		<category><![CDATA[Average]]></category>
		<category><![CDATA[numpy]]></category>
		<category><![CDATA[Numpy Array]]></category>
		<category><![CDATA[Python 3]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=473</guid>

					<description><![CDATA[<p>NumPy is a popular Python library for data science focusing on arrays, vectors, and matrices. This article introduces the np.average() function from the NumPy library. When applied to a 1D array, this function returns the average of the array values. When applied to a 2D array, NumPy simply flattens the array. The result is the ... <a title="How to Calculate the Average of a NumPy 2D Array?" class="read-more" href="https://blog.finxter.com/how-to-calculate-simple-average-of-numpy-array/" aria-label="Read more about How to Calculate the Average of a NumPy 2D Array?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-calculate-simple-average-of-numpy-array/">How to Calculate the Average of a NumPy 2D Array?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p><a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener" title="NumPy Tutorial – Everything You Need to Know to Get Started">NumPy </a>is a popular Python library for data science focusing on arrays, vectors, and matrices. This article introduces the <code>np.average()</code> function from the NumPy library. </p>



<p class="has-pale-cyan-blue-background-color has-background">When applied to a 1D array, this function returns the average of the array values. When applied to a 2D array, NumPy simply flattens the array. The result is the average of the flattened 1D array. Only if you use the optional <code>axis</code> argument, you can average along the rows or columns of the 2D array.</p>



<p>Here&#8217;s a visual overview first&#8212;we&#8217;ll discuss details later:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2021/02/average_numpy-1-1024x576.jpg" alt="NumPy np.average() 2D matrix" class="wp-image-23868" style="width:768px;height:432px" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/average_numpy-1-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2021/02/average_numpy-1-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2021/02/average_numpy-1-768x432.jpg 768w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p></p>



<p>Let&#8217;s start with the simple, flat case first.</p>



<h2 class="wp-block-heading">Average of Flattened 2D Array</h2>



<p>To calculate the average of all values in a two-dimensional NumPy array called <code>matrix</code>, use the <code>np.average(matrix)</code> function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import numpy as np
>>> matrix = np.array([[1, 0, 2],
                       [1, 1, 1]])
>>> np.average(matrix)
1.0</pre>



<p>This calculates the average of the flattened out matrix, i.e., it&#8217;s the same as calling <code>np.average([1, 0, 2, 1, 1, 1])</code> without the two-dimensional structuring of the data. </p>



<h2 class="wp-block-heading">Column Average of 2D Array</h2>



<p>To calculate the average separately for each column of the 2D array, use the function call <code>np.average(matrix, axis=0)</code> setting the axis argument to 0.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> np.average(matrix, axis=0)
array([1. , 0.5, 1.5])</pre>



<p>The resulting array has three average values, one per column of the input <code>matrix</code>. </p>



<h2 class="wp-block-heading">Row Average of 2D Array</h2>



<p>To calculate the average separately for each row of the 2D array, call <code>np.average(matrix, axis=1)</code> setting the axis argument to 1. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> np.average(matrix, axis=1)
array([1., 1.])</pre>



<p>The resulting array has two average values, one per row of the input <code>matrix</code>.</p>



<h2 class="wp-block-heading">NumPy Puzzle Average</h2>



<p>To test your skills and train your understanding of the np.average() function, here&#8217;s a code puzzle you may enjoy:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np

# stock prices (3x per day)
# [morning, midday, evening]
solar_x = np.array(
    [[2, 3, 4], # day 1
     [2, 2, 5]]) # day 2

print(np.average(solar_x))</pre>



<p><em>What is the output of this puzzle?</em><br>*Beginner Level* (solution below)</p>



<p>You can solve this code puzzle interactively on our Finxter.com puzzle app <a href="https://app.finxter.com/learn/computer/science/432" target="_blank" rel="noreferrer noopener" title="https://app.finxter.com/learn/computer/science/432">here</a>:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://app.finxter.com/learn/computer/science/432" target="_blank" rel="noopener"><img loading="lazy" decoding="async" width="1024" height="653" src="https://blog.finxter.com/wp-content/uploads/2021/02/image-55-1024x653.png" alt="" class="wp-image-23858" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/image-55-1024x653.png 1024w, https://blog.finxter.com/wp-content/uploads/2021/02/image-55-300x191.png 300w, https://blog.finxter.com/wp-content/uploads/2021/02/image-55-768x490.png 768w, https://blog.finxter.com/wp-content/uploads/2021/02/image-55.png 1270w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></figure>
</div>


<p>The puzzle has a matrix with two rows and three columns. The matrix gives the stock prices of the <code>solar_x</code> stock. Each row represents the prices for one day. The first column specifies the morning price, the second the midday price, and the third the evening price.</p>



<p>Note that NumPy calculates the average as the <a title="Python One Line Sum List" href="https://blog.finxter.com/python-one-line-sum-list/" target="_blank" rel="noreferrer noopener">sum</a> of all values divided by the number of values. The result is a <a title="Python float() Function" href="https://blog.finxter.com/python-float-function/" target="_blank" rel="noreferrer noopener">float </a>value.</p>



<p><br>Are you a master coder?<br><a rel="noopener" href="https://app.finxter.com/learn/computer/science/432" target="_blank">Test your skills now!</a></p>



<p>Note that the following tutorial may be interesting to you too:</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a href="https://blog.finxter.com/how-to-get-the-length-of-a-2d-numpy-array/" data-type="post" data-id="781650" target="_blank" rel="noreferrer noopener">How to Get the Length of a 2D NumPy Array</a></p>



<h2 class="wp-block-heading">Related Video</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Statistics: The average | Descriptive statistics | Probability and Statistics | Khan Academy" width="937" height="703" src="https://www.youtube.com/embed/uhxtUt_-GyM?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>
<p>The post <a href="https://blog.finxter.com/how-to-calculate-simple-average-of-numpy-array/">How to Calculate the Average of a NumPy 2D Array?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Index Elements in NumPy Arrays?</title>
		<link>https://blog.finxter.com/how-to-index-elements-numpy-arrays/</link>
					<comments>https://blog.finxter.com/how-to-index-elements-numpy-arrays/#respond</comments>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Fri, 12 Feb 2021 08:28:00 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scripting]]></category>
		<category><![CDATA[Indexing]]></category>
		<category><![CDATA[numpy]]></category>
		<category><![CDATA[Python 3]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=469</guid>

					<description><![CDATA[<p>NumPy is a popular Python library for data science for array, vector, and matrix computations. This puzzle introduces basic indexing of elements in NumPy arrays. Problem Formulation: How to index elements in NumPy arrays? Indexing 1D Arrays with Positive Indices The most simple use of indexing is with the square bracket notation and positive integers: ... <a title="How to Index Elements in NumPy Arrays?" class="read-more" href="https://blog.finxter.com/how-to-index-elements-numpy-arrays/" aria-label="Read more about How to Index Elements in NumPy Arrays?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-index-elements-numpy-arrays/">How to Index Elements in NumPy Arrays?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>NumPy is a popular Python library for data science for array, vector, and matrix computations. This puzzle introduces <strong>basic indexing of elements</strong> in <a href="https://blog.finxter.com/numpy-tutorial/" title="NumPy Tutorial – Everything You Need to Know to Get Started" target="_blank" rel="noreferrer noopener">NumPy arrays</a>.</p>



<p><strong>Problem Formulation: </strong>How to index elements in NumPy arrays?</p>



<h2 class="wp-block-heading">Indexing 1D Arrays with Positive Indices</h2>



<p>The most simple use of indexing is with the square bracket notation and positive integers:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import numpy as np
>>> a = np.array([1, 2, 3])
>>> a
array([1, 2, 3])
>>> a[0]
1
>>> a[1]
2
>>> a[2]
3</pre>



<p>If you use a positive index larger or equal than the number of elements in the array, Python will throw an <code><a href="https://blog.finxter.com/resolve-indexerror-list-assignment-index-out-of-range/" target="_blank" rel="noreferrer noopener" title="[Resolve] IndexError: List Assignment Index Out of Range">IndexError</a></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import numpy as np
>>> a = np.array([1, 2, 3])
>>> a[3]
Traceback (most recent call last):
  File "&lt;pyshell#19>", line 1, in &lt;module>
    a[3]
IndexError: index 3 is out of bounds for axis 0 with size 3</pre>



<h2 class="wp-block-heading">Indexing 1D Arrays with Negative Indices</h2>



<p>You can also use negative indices to access the array elements, starting with the last element and moving to the left:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import numpy as np
>>> a = np.array([8, 7, 5, 4, 9, 1, 9, 5])
>>> a[-1]
5
>>> a[-2]
9
>>> a[-3]
1
>>> a[-4]
9
>>> a[-5]
4
>>> a[-6]
5
>>> a[-7]
7
>>> a[-8]
8</pre>



<p>If you move further into the negative, Python will throw an <code><a href="https://blog.finxter.com/python-indexerror-list-index-out-of-range/" target="_blank" rel="noreferrer noopener" title="Python IndexError: List Index Out of Range (How to Fix This Stupid Bug)">IndexError</a></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> a[-9]
Traceback (most recent call last):
  File "&lt;pyshell#17>", line 1, in &lt;module>
    a[-9]
IndexError: index -9 is out of bounds for axis 0 with size 8</pre>



<h2 class="wp-block-heading">Indexing 2D Arrays NumPy</h2>



<p>If you use two-dimensional arrays, you can index individual elements with the square bracket notation and comma-separated index values, one per axis. The first index value gives the row index and the second index value gives the column index:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import numpy as np
>>> a = np.array([[42, 8, 7],
		  [99, 3, 4]])
>>> a[0, 0]
42
>>> a[1, 2]
4
>>> a[1, 1]
3</pre>



<p>You can also use negative indexing on one or both axes.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> a[-1, -1]
4</pre>



<p>If you access elements outside the bound of the maximal possible index, Python raises an <code>IndexError</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> a[2, 1]
Traceback (most recent call last):
  File "&lt;pyshell#28>", line 1, in &lt;module>
    a[2, 1]
IndexError: index 2 is out of bounds for axis 0 with size 2</pre>



<h2 class="wp-block-heading">NumPy Array Indexing Multi-dimensional Arrays</h2>



<p>If you use multi-dimensional arrays, you can index individual elements with the square bracket notation and comma-separated index values, one per axis.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import numpy as np
>>> a = [[[1, 1], [2, 3]],
	 [[4, 3], [8, 9]]]
>>> a = np.array(a)
>>> a[0, 0, 0]
1
>>> a[0, 0, 1]
1
>>> a[0, 1, 0]
2
>>> a[0, 1, 1]
3
>>> a[1, 0, 0]
4
>>> a[1, 0, 1]
3
>>> a[1, 1, 0]
8
>>> a[1, 1, 1]
9</pre>



<p><strong>As a rule of thumb:</strong> the first element in the comma-separated square bracket notation identifies the outermost axis, the second element the second-outermost axis, and so on. </p>



<h2 class="wp-block-heading">NumPy Array Indexing Puzzle</h2>



<p>Train your skills by solving the following NumPy puzzle about indexing and basic array arithmetic:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np

# air quality index AQI data
hong_kong = np.array([42, 40, 41, 43, 44, 43])
new_york = np.array([30, 31, 29, 29, 29, 30])
montreal = np.array([11, 11, 12, 13, 11, 12])

hk_mean = (hong_kong[0] + hong_kong[-1]) / 2.0
ny_mean = (new_york[1] + new_york[-3]) / 2.0
m_mean = (montreal[1] + montreal[-0]) / 2.0

print(hk_mean)
print(ny_mean)
print(m_mean)</pre>



<p><em>What is the output of this puzzle?</em><br>*Beginner Level* (solution below)</p>



<p>You can solve this puzzle on our interactive Finxter app and track your skill level here:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><a href="https://app.finxter.com/learn/computer/science/431" target="_blank" rel="noopener"><img loading="lazy" decoding="async" width="1024" height="668" src="https://blog.finxter.com/wp-content/uploads/2021/02/image-53-1024x668.png" alt="" class="wp-image-23791" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/image-53-1024x668.png 1024w, https://blog.finxter.com/wp-content/uploads/2021/02/image-53-300x196.png 300w, https://blog.finxter.com/wp-content/uploads/2021/02/image-53-768x501.png 768w, https://blog.finxter.com/wp-content/uploads/2021/02/image-53.png 1250w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></figure></div>



<p>The puzzle analysis data from the real-time air quality index (AQI) for the three cities Hong Kong, New York, and Montreal. The index data aggregates various factors that influence the air quality such as respirable particulate matter, ozone, and nitrogen dioxide. The goal is to compare the air quality data for the three cities. To show how indexing works, we use different indexing schemes to access two data values for each city. Then, we normalize the data by 2.0.</p>



<p>You can use positive or negative indices. For positive indices, use 0 to access the first element and increment the index by 1 to index each subsequent element. For negative indices, use -1 to access the last element and decrement the index by 1 to access each previous element. It&#8217;s as simple as that.</p>



<p>Are you a master coder?<br><a href="https://app.finxter.com/learn/computer/science/431" target="_blank" rel="noopener">Test your skills now!</a></p>



<h2 class="wp-block-heading">Related Video</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="5- NumPy Array Indexing 1/2" width="937" height="703" src="https://www.youtube.com/embed/yDOy5UewRZM?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p></p>
<p>The post <a href="https://blog.finxter.com/how-to-index-elements-numpy-arrays/">How to Index Elements in NumPy Arrays?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.finxter.com/how-to-index-elements-numpy-arrays/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>A Simple Recommendation System Using Pandas corrwith() Method</title>
		<link>https://blog.finxter.com/a-simple-recommendation-system-with-pandas/</link>
		
		<dc:creator><![CDATA[Lukas]]></dc:creator>
		<pubDate>Fri, 30 Oct 2020 17:16:10 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Pandas Library]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Pandas]]></category>
		<category><![CDATA[Python 3]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=16134</guid>

					<description><![CDATA[<p>What is a Recommendation System? If you use Netflix or Amazon you have already seen the results of recommendation systems &#8211; movie or item recommendations that fit your taste or needs. So, at its core a recommendation system is a statistical algorithm that computes similarities based on previous choices or features and recommends users which ... <a title="A Simple Recommendation System Using Pandas corrwith() Method" class="read-more" href="https://blog.finxter.com/a-simple-recommendation-system-with-pandas/" aria-label="Read more about A Simple Recommendation System Using Pandas corrwith() Method">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/a-simple-recommendation-system-with-pandas/">A Simple Recommendation System Using Pandas corrwith() Method</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">What is a Recommendation System?</h2>



<p>If you use Netflix or Amazon you have already seen the results of recommendation systems &#8211; movie or item recommendations that fit your taste or needs. So, at its core a recommendation system is a statistical algorithm that computes similarities based on previous choices or features and recommends users which movie to watch or what else they might need to buy.</p>



<h2 class="wp-block-heading">How Does a Recommendation System Work?</h2>



<p>Assume that persons A and B like a movie M1 and person A also likes movie M2. Now, we can conclude that person B will also like movie M2 with a high probability. Well, that&#8217;s very little data and probably a rather imprecise prediction. Yet, it illustrates how collaborative filtering works. In a real world application we would need much more data to make good recommendations. The recommendation algorithms based this concept are called <strong>collaborative filtering</strong>.</p>



<p>Another popular way to recommend items is so called <strong>content-based filtering</strong>. Content-based filtering computes recommendations based on similarities of items or movies. In the case of movies we could look at different features like: genre, actors, &#8230; to compute similarity.<br>If a user liked a given movie, the probability is high that the user will also like similar movies. Thus, it makes sense to recommend movies with a high similarity to those the user liked.</p>



<h2 class="wp-block-heading">Implementing a Recommendation System</h2>



<p>If you want to understand the code below better, make sure to <strong>sign up for our free email course &#8220;Introduction to Pandas and Data Science&#8221;</strong> on our <a href="https://blog.finxter.com/email-academy/">Email Academy</a>. Throughout the course, we develop a recommendation system for movies. At its core, there is the method <em>corrwith()</em> from the Pandas library.</p>



<p>This is the final implementation of our recommendation system:</p>



<figure class="wp-block-image size-large is-style-default"><img loading="lazy" decoding="async" width="924" height="713" src="https://blog.finxter.com/wp-content/uploads/2020/10/code-1.png" alt="" class="wp-image-16137" srcset="https://blog.finxter.com/wp-content/uploads/2020/10/code-1.png 924w, https://blog.finxter.com/wp-content/uploads/2020/10/code-1-300x231.png 300w, https://blog.finxter.com/wp-content/uploads/2020/10/code-1-768x593.png 768w, https://blog.finxter.com/wp-content/uploads/2020/10/code-1-150x116.png 150w" sizes="auto, (max-width: 924px) 100vw, 924px" /><figcaption><strong>Download the MovieLens data set from:</strong> https://grouplens.org/datasets/movielens/latest/</figcaption></figure>



<h2 class="wp-block-heading">How to Use Pandas corrwith() Method?</h2>



<p>The Pandas object DataFrame offers the method <em>corrwith()</em> which computes pairwise correlations between DataFrames or a DataFrame and a Series. With the parameter axis, you can either compute correlations along the rows or columns. Here is the complete signature, blue parameters are optional and have default values.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="57" src="https://blog.finxter.com/wp-content/uploads/2020/11/signature_corrwith-1024x57.png" alt="" class="wp-image-16255" srcset="https://blog.finxter.com/wp-content/uploads/2020/11/signature_corrwith.png 1024w, https://blog.finxter.com/wp-content/uploads/2020/11/signature_corrwith-300x17.png 300w, https://blog.finxter.com/wp-content/uploads/2020/11/signature_corrwith-768x43.png 768w, https://blog.finxter.com/wp-content/uploads/2020/11/signature_corrwith-1536x86.png 1536w, https://blog.finxter.com/wp-content/uploads/2020/11/signature_corrwith-150x8.png 150w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p><strong>The arguments in detail:</strong><br>1.) other: A Series or DataFrame with which to compute the correlation.<br>2.) axis: Pass 0 or &#8216;index&#8217; to compute correlations column-wise, 1 or &#8216;columns&#8217; for row-wise.<br>3.) drop: Drop missing indices from result.<br>4.) method: The algorithm used to compute the correlation. You can either choose from: &#8216;pearson&#8217;, &#8216;kendall&#8217; or &#8216;spearman&#8217; or implement your own algorithm. So, either you pass one of the three strings or a callable.<br><br>Here is a practical example:</p>



<pre class="wp-block-code"><code>import pandas as pd<br><br>ratings = {<br>       'Spider Man':&#91;3.5, 1.0, 4.5, 5.0],<br>       'James Bond':&#91;1.0, 2.5, 5.0, 4.0],<br>       'Titanic':&#91;5.0, 4.5, 1.0, 2.0] <br>}<br><br>new_movie_ratings = pd.Series(&#91;2.0, 2.5, 5.0, 3.5])<br>all_ratings = pd.DataFrame(ratings)<br><br>print(all_ratings.corrwith(new_movie_ratings))</code></pre>



<p>From a given dictionary of lists (ratings) we create a DataFrame. This DataFrame has three columns and four rows. Each column contains the movie ratings of all four users.<br>The Series new_movie_ratings contains the ratings for a new movie of all four users.<br>Using the method <em>corrwith()</em> on the DataFrame we get the correlation between the new ratings and the old ones.<br>The output of the snippet above is:<br></p>



<pre class="wp-block-preformatted">Spider Man    0.566394
James Bond    0.953910
Titanic      -0.962312</pre>



<p>As you can see, the new movie has the highest correlation with the James Bond movie. This means, a recommendation system which works purely based on ratings, should recommend the James Bond movie to users that liked the new movie.<br>Yet, what exactly is correlation?</p>



<h2 class="wp-block-heading">What is Correlation?</h2>



<p>Correlation describes the statistical relationship between two entities. This is to say, it&#8217;s how two variables move in relation to one another. Correlation is given as a value between -1 and +1. <strong>However, correlation is not causation!</strong></p>



<p>There are three types of correlation:</p>



<ul class="wp-block-list"><li><strong>Positive correlation:</strong><br>A positive correlation is a value in the range 0.0 &lt; c &lt;= 1.0. A correlation of 1.0 means that if the first variable moves up, the second one will also move up. This relationship is weaker if the correlation is lower than 1.0.</li><li><strong>Negative correlation:</strong><br>A negative correlation is a value in the range 0.0 &gt; c &gt;= -1.0. Negative correlation means that two variable have the opposite behaviour. So, if the first one moves up the second one moves down.</li><li><strong>Zero or no correlation:</strong><br>A correlation of zero means there is no relationship between the two variables. If the first variable moves up, the second one may do anything else.</li></ul>



<h2 class="wp-block-heading">More Pandas DataFrame Methods</h2>



<p>Feel free to learn more about the previous and next <a href="https://blog.finxter.com/pandas-quickstart/" data-type="post" data-id="16511" target="_blank" rel="noreferrer noopener">pandas</a> DataFrame methods (alphabetically) here:</p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<div class="wp-block-buttons alignwide is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button has-custom-width wp-block-button__width-75 is-style-fill"><a class="wp-block-button__link" href="https://blog.finxter.com/pandas-dataframe-corr-method/" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f448.png" alt="👈" class="wp-smiley" style="height: 1em; max-height: 1em;" /> df.corr()</a></div>
</div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<div class="wp-block-buttons alignwide is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button has-custom-width wp-block-button__width-75 is-style-fill"><a class="wp-block-button__link" href="https://blog.finxter.com/pandas-dataframe-count-method/" target="_blank" rel="noreferrer noopener">df.count() <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></a></div>
</div>
</div>
</div>



<p>Also, check out the full cheat sheet overview of <a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-dataframe-methods/" data-type="post" data-id="344397" target="_blank">all Pandas DataFrame methods</a>.</p>
<p>The post <a href="https://blog.finxter.com/a-simple-recommendation-system-with-pandas/">A Simple Recommendation System Using Pandas corrwith() Method</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Become a Python Freelancer&#8212;and Earn $1,000 on the Side? [A Step-by-Step Tutorial]</title>
		<link>https://blog.finxter.com/how-to-earn-1000-on-the-side-as-a-python-freelancer-a-step-by-step-tutorial/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Wed, 19 Aug 2020 22:02:00 +0000</pubDate>
				<category><![CDATA[Coding Business]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Freelancing]]></category>
		<category><![CDATA[Productivity]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Fiverr]]></category>
		<category><![CDATA[Freelancer]]></category>
		<category><![CDATA[learn python]]></category>
		<category><![CDATA[Python 3]]></category>
		<category><![CDATA[Upwork]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=820</guid>

					<description><![CDATA[<p>Do you want to earn money as a Python freelancer? But you just start out learning Python? This article leads you step-by-step through the adventure of becoming a Python freelancer. Learn about the exact steps you need to do to become a Python freelancer - starting out as a Python newbie. Without losing any time, let's dive into the 7 steps of becoming a Python freelancer.</p>
<p>The post <a href="https://blog.finxter.com/how-to-earn-1000-on-the-side-as-a-python-freelancer-a-step-by-step-tutorial/">How to Become a Python Freelancer&#8212;and Earn $1,000 on the Side? [A Step-by-Step Tutorial]</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Don&#8217;t want to read the whole article? Here&#8217;s a summary of the steps:</p>



<ol class="wp-block-list">
<li><strong>Motivation:</strong> Watch the free video about the <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">state-of-the-art of Python freelancing</a> (opens in a new tab).</li>



<li><strong>Training</strong>: <a href="https://blog.finxter.com/become-python-freelancer-course/" target="_blank" rel="noreferrer noopener">Reach Python freelancer level</a> (~40-80 hours).</li>



<li><strong>Confidence</strong>: Complete 3 <a href="https://www.freelancer.com/archives/" target="_blank" rel="noreferrer noopener">archived Python projects</a> for learning and read business books such as <a href="https://amzn.to/2Re2JqO" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2Re2JqO">Leaving the Rat Race with Python</a> (Amazon). </li>



<li><strong>Platform</strong>: Create accounts at <a href="http://upwork.com" target="_blank" rel="noreferrer noopener">Upwork </a>and <a href="http://fiverr.com" target="_blank" rel="noreferrer noopener">Fiverr</a>.</li>



<li><strong>Credibility</strong>: Get your 5-star ratings for small $15 Python projects.</li>



<li><strong>Scale</strong>: Ladder up your hourly wage.</li>



<li><strong>Pro tip</strong>: Create a personal website and drive paid traffic to it.</li>
</ol>



<p><em>Do you want to earn money as a Python freelancer? But you are just starting in Python? <strong>This article leads you step-by-step through the adventure of becoming a Python freelancer.</strong> You&#8217;ll learn about the exact steps you need to do to become a Python freelancer&#8212;starting as a Python newbie. </em></p>



<p><em>And if you&#8217;re serious about your next-level career step, join my FREE webinar (on the Finxter blog) <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">&#8220;How to Build Your High-Income Skill Python&#8221;</a> where I&#8217;ll show you exactly <strong>how I went from earning $0 to full-time income and beyond</strong>&#8212;as a Python freelance developer.</em></p>



<p>Before we start, let&#8217;s answer an important question: <strong>is Python freelancing worth it?</strong> I compiled the pros and cons from different places online (e.g. <a href="https://blog.teamtreehouse.com/python-freelancing-good-bad-ugly">here</a>) and added my own experience in the freelancing space&#8212;both as a client and as a Python freelancer.</p>


<div class="wp-block-image">
<figure class="aligncenter is-resized"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2019/10/GoodBadUgly-1024x576.jpg" alt="Python Freelancing Pros and Cons" class="wp-image-4768" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2019/10/GoodBadUgly.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2019/10/GoodBadUgly-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2019/10/GoodBadUgly-768x432.jpg 768w" sizes="auto, (max-width: 768px) 100vw, 768px" /></figure>
</div>


<p>Do you want to develop the skills of a <strong>well-rounded Python professional</strong>&#8212;while getting paid in the process? Become a Python freelancer and order your book <a href="https://amzn.to/2Re2JqO" target="_blank" rel="noreferrer noopener"><strong>Leaving the Rat Race with Python</strong></a> on Amazon (<em>Kindle/Print</em>)!</p>



<div class="wp-block-image"><figure class="aligncenter size-medium is-resized"><a href="https://amzn.to/2Re2JqO" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2020/08/final_cover-200x300.jpg" alt="Leaving the Rat Race with Python Book" class="wp-image-11850" width="200" height="300" srcset="https://blog.finxter.com/wp-content/uploads/2020/08/final_cover-200x300.jpg 200w, https://blog.finxter.com/wp-content/uploads/2020/08/final_cover-scaled.jpg 683w, https://blog.finxter.com/wp-content/uploads/2020/08/final_cover-768x1152.jpg 768w, https://blog.finxter.com/wp-content/uploads/2020/08/final_cover-1024x1536.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2020/08/final_cover-1365x2048.jpg 1365w, https://blog.finxter.com/wp-content/uploads/2020/08/final_cover-150x225.jpg 150w" sizes="auto, (max-width: 200px) 100vw, 200px" /></a></figure></div>



<p><em>Without losing any time, let&#8217;s dive into the 7 steps of becoming a Python freelancer.</em></p>



<p><strong>Table of contents:</strong></p>



<ol class="wp-block-list">
<li><a href="#money">How much money ($$$) you can earn as a Python freelancer</a></li>



<li><a href="#confidence">How to gain confidence that you can give value to the marketplace?</a></li>



<li><a href="#basics">How to start learning the basics of Python? </a></li>



<li><a href="#independence">How to make yourself independent from freelancing platforms?</a></li>



<li><a href="#attractive">How to become an attractive freelancer?</a></li>



<li><a href="#projects">How to find practical Python projects for learning?</a></li>



<li><a href="#start">When to stop learning and start doing real Python projects?</a></li>



<li><a href="#place-to-start">What is a good place to start Python freelancing?</a></li>
</ol>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2018/07/python-logo-master-v3-TM.png" alt="Python Logo" class="wp-image-573" width="456" height="154" srcset="https://blog.finxter.com/wp-content/uploads/2018/07/python-logo-master-v3-TM.png 601w, https://blog.finxter.com/wp-content/uploads/2018/07/python-logo-master-v3-TM-300x101.png 300w" sizes="auto, (max-width: 456px) 100vw, 456px" /></figure>



<h2 class="wp-block-heading" id="money">1. How Much Money ($$$) Can You Earn as a Python Freelancer?</h2>



<p>As a Python developer, you can expect to earn between $10 and $80 per hour with an average salary of $51 (<a href="https://www.ziprecruiter.com/Salaries/How-Much-Does-a-Freelance-Python-Developer-Make-an-Hour" target="_blank" rel="noreferrer noopener">source</a>). I know the variation of the earning potential is high but so is the quality of the Python freelancers in the wild. Take the average salary as a starting point and add +/- 50% to account for your level of expertise. <a href="https://blog.finxter.com/whats-the-hourly-rate-of-a-python-freelancer/" target="_blank" rel="noreferrer noopener">In this blog article</a>, I summarized all credible sources online about how much you can earn as a Python coder. <strong>The key takeaway is that intermediate-level Python freelancers today earn six figures easily ($100,000 yearly gross income or more)</strong>:</p>


<div class="wp-block-image">
<figure class="aligncenter is-resized"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2019/04/course_image-1024x576.jpg" alt="How Much Can You Earn as a Python Freelancer?" class="wp-image-2683" width="768" height="432" title="Python Developer Hourly Rate" srcset="https://blog.finxter.com/wp-content/uploads/2019/04/course_image.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2019/04/course_image-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2019/04/course_image-768x432.jpg 768w, https://blog.finxter.com/wp-content/uploads/2019/04/course_image-100x56.jpg 100w, https://blog.finxter.com/wp-content/uploads/2019/04/course_image-670x377.jpg 670w" sizes="auto, (max-width: 768px) 100vw, 768px" /></figure>
</div>


<p>This data is based on various sources:</p>



<ul class="wp-block-list">
<li><strong>Codementor </strong>argues that the average freelancer earns between $61 and $80 in 2019: <a href="https://www.codementor.io/freelance-rates/python-developers" target="_blank" rel="noreferrer noopener">source</a></li>



<li>This <strong>Subreddit </strong>gives a few insights about what some random freelancers earn per hour (it&#8217;s usually more than $30 per hour): <a href="https://www.reddit.com/r/Python/comments/25prpv/python_freelancers_what_do_you_do_and_how_much_do/" target="_blank" rel="noreferrer noopener">source</a></li>



<li><strong>Ziprecruiter </strong>finds that the average Python freelancer earns $52 per hour in the US. This is equivalent to $8,980 per month or $107,000 per year: <a href="https://www.ziprecruiter.com/Salaries/Freelance-Python-Developer-Salary" target="_blank" rel="noreferrer noopener">source</a></li>



<li><strong>Payscale </strong>is more pessimistic and estimates the average hourly rate around $29 per hour: <a href="https://www.payscale.com/research/US/Skill=Python/Hourly_Rate" target="_blank" rel="noreferrer noopener">source</a></li>



<li>As a Python developer, you can expect to earn between $10 and $80 per hour with an average salary of $51 (<a href="https://www.ziprecruiter.com/Salaries/How-Much-Does-a-Freelance-Python-Developer-Make-an-Hour">source</a>).</li>
</ul>



<p>If you work on the side, let&#8217;s make it 8 hours each Saturday, you will earn $400 extra per week &#8211; or $1600 per month (before taxes). Your hourly rate will be a bit lower because you have to invest time finding freelancing clients &#8211; up to 20% of your total time.</p>



<p><strong>Action steps:</strong></p>



<ul class="wp-block-list">
<li>Write down how many hours you can invest per week.</li>



<li>Write down your goal hourly rate.</li>
</ul>



<h2 class="wp-block-heading" id="confidence">2. How to Gain Confidence That You Can Give Value to the Marketplace?</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Get Started as a Freelance Developer?" width="937" height="527" src="https://www.youtube.com/embed/cPVN-ACwpO8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Before becoming a Python freelancer, you have to learn the very basics of Python. What&#8217;s the point of offering your freelancer services when you can not even write Python code?</p>



<p>Having said this, it&#8217;s more likely that you live on the other extreme. You do not want to offer your services before you don&#8217;t feel 100% confident about your skills. Unfortunately, this moment never arrives. I have met hundreds of advanced coders, who are still not confident in selling their services. They cannot overcome their self-woven system of limiting believes and mental barriers.</p>



<p>Can I tell you a harsh truth? You won&#8217;t join the top 1% of the Python coders with high probability (a hard statistical fact). But never mind. Your services will still be valuable to clients who either have less programming skills (there are plenty of them) or little time (a big part of the rest). &nbsp;Most clients are happy to outsource the complex coding work to focus on their key result areas.</p>



<p>Regardless of your skill level, the variety of Python projects is huge. There are simple projects for $10 which an experienced coder can solve in 5 minutes. And there are complex projects that take months and promise you large payments of $100 to $1000 after completing each milestone.</p>



<p>You can be sure that you will find projects in your skill level.</p>



<p><strong>Action steps:</strong></p>



<ul class="wp-block-list">
<li>Take your time to browse all the <a href="https://www.freelancer.com/archives/">archived Python freelance projects</a>.</li>



<li>Select 3 projects that you think you can solve in the price range ($10-$50).</li>



<li>Write down in which direction you want to go first (keep the projects in mind that you just selected): data science, web scraping, application development, scripting, &#8230;</li>
</ul>



<h2 class="wp-block-heading" id="basics">3. How to Start Learning the Basics of Python?</h2>



<p>Before you start with practical projects though, you should invest 10-20 hours in refreshing your basic Python skills. This is not much of a time commitment &#8211; after all, you are learning a high-income skill. You can learn a lot in 20 hours if you do it right. The key is to learn probabilistically by mastering important subskills first. Watch this great TED talk about what you can achieve in 20 hours.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="The first 20 hours -- how to learn anything | Josh Kaufman | TEDxCSU" width="937" height="527" src="https://www.youtube.com/embed/5MgBikgcWnY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>So what’s the best way to learn probabilistically? Simple. Use the <a href="https://blog.finxter.com/the-80-20-principle-in-programming/" target="_blank" rel="noreferrer noopener" title="The 80/20 Principle in Programming">80/20 principle</a>. This famous principle states that 80% of the causes lead to 20% of the effects. Get rid of the 80% low-value tasks and focus instead of the 20% of causes with 80% of the effects.</p>



<p>The best way to learn 80% of the skills in 20% of the time, is via Python cheat sheets.<a href="https://blog.finxter.com/collection-5-cheat-sheets-every-python-coder-must-own/" target="_blank" rel="noreferrer noopener"> I have summarized the 5 best Python cheat sheet in this article.</a> Download the cheat sheets and spend your first 20 hours in learning them thoroughly. Or even better: print them and post them to your office wall.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><a href="https://blog.finxter.com/subscribe/" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2018/10/Cheat-sheet-python-Keywords1-1-791x1024.png" alt="" class="wp-image-824" width="593" height="768"/></a></figure>
</div>


<p><strong>Action steps:</strong></p>



<ul class="wp-block-list">
<li>Download the cheat sheet: <a href="https://perso.limsi.fr/pointal/_media/python:cours:mementopython3-english.pdf" target="_blank" rel="noreferrer noopener">Python 3 Cheat Sheet</a>.</li>



<li>Subscribe to the FREE cheat sheet course: <a href="https://blog.finxter.com/subscribe/" target="_blank" rel="noreferrer noopener">The Ultimate Python Cheat Sheet Course (5x Email Series).</a></li>
</ul>



<h2 class="wp-block-heading" id="independence">4. How to Gain Independence from Freelancing Platforms?</h2>



<p>Freelancing platforms offer you convenience and speed in starting your own freelancing business. Examples are <a href="http://upwork.com" target="_blank" rel="noreferrer noopener">Upwork</a>, <a href="http://freelancer.com" target="_blank" rel="noreferrer noopener">Freelancer</a>, or even <a href="http://fiverr.com" target="_blank" rel="noreferrer noopener">Fiverr</a>. Some of those platforms (e.g. Upwork) will manually check your profile, so it will take some time to sign up. The reason is that these platforms receive thousands of applications every day. They have to be selective to guarantee a certain quality of service. I have read about many cases where Upwork rejected freelancers with attractive profiles.</p>



<p>On the first impression, these platforms seem to be very attractive for your emerging freelance business. But be careful! Many existing freelancers heavily rely on these freelancing platforms. By using a platform such as Upwork, you make yourself vulnerable. Your income depends on the decisions of the platform owners. And don&#8217;t think they have your best interest at heart. For example, Upwork already takes a 20% cut (!) from your hourly rate, just for brokering your services to potential clients. And their cut is pre-tax. In other words, you are working the first 12 minutes of each hour for Upwork (and the next 28 minutes for the government).</p>



<p>What are some risks of depending on a freelancing platform? The platform owners can suddenly increase their cut. They can throw you from the platform for no reason whatsoever. They will stop sending clients your way as soon as their algorithm decides that you are not the optimal fit for a client project. The main problem is that you don&#8217;t control your customer base. On the back of ONLY these platforms, you can not build a robust and sustainable business.</p>



<p>So what’s the alternative? If you are serious about becoming a Python freelancer, setting up your own website is the way to go. This allows you to offer your services to clients all over the world. You establish trust and clients perceive you as a professional freelancer. Use freelancing platforms to attract clients, but retain them for yourself.</p>



<p>To increase your conversions, add testimonials to your website. Keep collecting them during each of your freelancing activities. Of course, this is a bit harder than just setting up a freelancing account on Upwork. But it&#8217;s a much more sustainable foundation of your freelancing business. A nice plus is that your professional website sets you apart from your competition. It increases your chances of getting clients.</p>



<p>Only after creating your own web presence, you should use these platforms to get new clients. Make sure to always refer to your professional website within any project application.</p>



<p>How do you retain clients beyond the first project? Focus on always over-delivering to new clients! Make them happy. Ask them to contact you directly the next time they need a similar service. And give them a special offer for the next freelancing service. Finally, ask them for referrals and testimonials after the job is done.</p>



<p>As you establish a growing client base you control, you will find yourself using Upwork, Freelancer, and Fiverr less and less. Because of that, your profit margin will grow over time. Not only will your income increase, but it will also stand on a solid foundation. You own the foundation of your business (your client base).</p>



<p><strong>Action steps:</strong></p>



<ul class="wp-block-list">
<li>Get a meaningful domain such as (e.g. “python-freelancing-services.com”).</li>



<li>Create a WordPress page introducing your services.</li>



<li>Create profiles on <a href="http://Freelancer.com" target="_blank" rel="noreferrer noopener">Freelancer.com</a>, <a href="http://Upwork.com" target="_blank" rel="noreferrer noopener">Upwork.com</a>, and <a href="http://Fiverr.com" target="_blank" rel="noreferrer noopener">Fiverr.com</a>.</li>
</ul>



<h2 class="wp-block-heading" id="attractive">5. How to Become an Attractive Freelancer?</h2>



<p>In the last months, I got a lot of experience using freelancer services as a client. My goal was to improve the <a href="https://finxter.com" target="_blank" rel="noreferrer noopener">Finxter.com</a> website to test your Python skills and my <a href="https://blog.finxter.com/coffee-break-python/" target="_blank" rel="noreferrer noopener" title="Coffee Break Python">book “Coffee Break Python”</a>. A similar pattern emerged every time I posted a new project description. A few hours after posting the description, several freelancers applied. The competition was fierce. But within minutes, I had subconsciously chosen an inner circle of high-potential candidates. There was not one case, where I chose a freelancer who could not immediately pass the entry barriers of my subconscious mind.</p>



<p>You want to be in that inner circle. To get there, you must be appealing to the subconscious mind. The following factors will give you a psychological advantage when competing for a freelance job.</p>



<p><strong>Use the power of reciprocity.</strong></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>“Reciprocity is a social norm of responding to a positive action with another positive action, rewarding kind actions.”<br></p>
<cite><a href="https://en.wikipedia.org/wiki/Reciprocity_(social_psychology)">Wikipedia</a></cite></blockquote>



<p>This principle is the most important insight which I gained from my own experience of hiring freelancers.</p>



<p>For example, I published a project to check the Python code of my recent <a href="http://viewbook.at/CoffeeBreakPython">Python programming book</a>. The project description stated that I intended to edit the code to make it more Pythonic. This project was important to me because I want to provide high quality and readability for advanced coders. Immediately, several freelancers applied for the job. They went into “competition-mode” bragging about their credentials. They tried to convince me that they are the perfect fit for this project. I selected a few candidates but was not 100% sure about any of them.</p>



<p>Towards the end of the application phase, a new freelancer registered interest with an unusual application. Instead of talking about his credentials, he focused on the project itself. He dived right into the project and submitted annotated and corrected Python code snippets &#8211; improving upon those I provided as sample files. He gave them to me for free. Of course, I knew that he purposely used the reciprocity rule to get the job. Yet, I was immediately hooked and felt a strong obligation to reward him for his work &#8211; and gave him the job.</p>



<p>This is the power of the reciprocity rule. &nbsp;</p>



<p><strong>Don’t hide your titles and credentials.</strong></p>



<p>They still work. When you apply for a job and you have the title “Prof.”, “Ph.D.”, or “MSc” in a relevant area, you have gained immediate credibility. In most cases, it will set you apart from the other freelancers without strong credentials or titles.</p>



<p>Note that credentials are not limited to the academic world. You should also highlight your practical achievements such as your websites, shiny projects, or certificates. Be creative.</p>



<p><strong>Invest time in your profile picture.</strong></p>



<p>You wouldn’t believe the powerful impact of your profile picture on your chances of getting the job. Many coders don&#8217;t focus too much on appearance. Don’t do this. Smile, dress professionally, use a natural image background. Need insider tips? Check out <a href="https://www.freelancer.com/community/articles/how-can-i-improve-my-profile-image">this article from freelancer.com</a>.</p>



<p><strong>Don’t compete on price.</strong></p>



<p>Forget about it. Competing on price is a race towards zero. You can not win. There is always a cheaper freelancer and some of them WILL apply for the same projects.</p>



<p>It&#8217;s true, some clients look for the cheapest freelancer who barely finishes the task. But most clients will choose high quality and predictability over price. What would you do if you were a business owner who works 60 hour weeks to push his website? You love your baby and don&#8217;t want a cheap freelancer to mess around with it. A freelancer that offers a service at a very cheap rate is also perceived as shipping cheap quality. After all, you ain&#8217;t cheap if you are good.</p>



<p>So what is the value of an hour of your work? Multiply this number with 1.5. Do this for two reasons: You tend to underestimate your value to the marketplace, and you should constantly push yourself to improve (that&#8217;s what you want, isn&#8217;t it?). Now you have your number. NEVER work for an hourly rate below that number! And keep pushing it &#8211; the sky is the limit!</p>



<p><strong>Action steps:</strong></p>



<ul class="wp-block-list">
<li>Collect Python certificates. For example, use our web app Finxter to <a href="https://app.finxter.com/certificate">certify your Python skill level</a>.</li>



<li>Get an awesome <a href="https://www.freelancer.com/community/articles/how-can-i-improve-my-profile-image">profile picture</a>.</li>



<li>Give something to each potential client. For example, invest some time creating a prototype solution. This will greatly improve your acceptance rate and ultimately save a lot of time!</li>
</ul>



<h2 class="wp-block-heading" id="projects">6. How to Find Practical Python Projects for Learning?</h2>



<p>This is the most important question for you as a beginner. Most developers know that they should never do premature code optimizations. But they do premature skill optimizations all the time. Don&#8217;t do that. Laser focus your time to learn the most important skills with the highest priority.<br></p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Practical Python Projects -- How Real Freelancers Earn Money in 2019" width="937" height="527" src="https://www.youtube.com/embed/dLPqizZoZZo?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>One of my articles on this blog shows you <a href="https://blog.finxter.com/how-real-freelancers-earn-money-in-2019-10-practical-python-projects/">10 highly practical freelancer projects</a> on which real freelancers worked to earn money. Again, find highly practical code projects for any skill level at <a href="https://freelancer.com/archives">freelancer.com/archives</a>.</p>



<p>These archived freelancing projects are goldmines. Invest time to study them carefully. If you do so, you will learn about the practical Python problems that clients seek to solve. You will learn about the patterns of Python problems “in the wild”. This knowledge will guide you in your efforts of becoming more valuable to the marketplace. In contrast to millions of other aspiring coders, you will develop a practical Python skillset tailored to your interest level.</p>



<p><strong>Action steps:</strong></p>



<ul class="wp-block-list">
<li>Browse the <a href="https://www.freelancer.com/archives/">archive of freelancing Python projects</a>.</li>



<li>Find projects you like in your difficulty level (read my article about <a href="https://blog.finxter.com/how-real-freelancers-earn-money-in-2019-10-practical-python-projects/">10 highly </a><a href="https://blog.finxter.com/how-real-freelancers-earn-money-in-2019-10-practical-python-projects/" target="_blank" rel="noreferrer noopener">practical freelancer projects</a> with which real freelancers earned money).</li>



<li>Complete these projects.</li>
</ul>



<h2 class="wp-block-heading" id="start">7. When to Stop Learning and Start Doing Real Python Projects?</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Freelance Programmer -- When To Start Taking Projects?" width="937" height="527" src="https://www.youtube.com/embed/D6RXsU1kVYg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p><em>Start with real projects immediately. Use the freelance.com archive to find practical projects if you do not feel confident, yet. But don’t wait too long &#8211; even if you are a beginner programmer. Set aside 10 minutes per day or so to watch out for interesting projects. When you have solved archived projects, chances are that clients have similar projects that they want to outsource. To drive traffic to your own freelancer website, you could write a blog post about the topic. You could even drive traffic via Facebook ads if you need to. Try to establish your own brand as soon as possible. Learn with real clients. Learn practical skills first. What are the practical skills? You can only learn them by working on real projects. Don’t lose any more time. Start today!</em></p>



<p><strong>My answer is very simple: start right away — no matter your current skill level.</strong></p>



<p>But I know that for many Python coders just starting out, it’s very difficult to start right away. Why? Because they don’t have the confidence, yet, to start taking on projects.</p>



<p>And the reason is that they never have quite finished a Python project — and, of course, they are full of doubts and low self-esteem. They fear not being able to finish through with the freelancer project and earn the criticism of their clients.</p>



<p>If you have to overcome this fear first, then I would recommend that you start doing some archived freelancer projects. I always recommend a great resource where you can find these <a href="https://www.freelancer.com/archives/">archived freelancer projects</a>. On this resource, you’ll find not only a few but all the freelancer projects in different areas — such as Python, data science, and machine learning — that have ever been published at the Freelancer.com platform. There are thousands of such projects.</p>



<p>Unfortunately, many projects published there are crappy and it’ll take a lot of time finding suitable projects. To relieve you from this burden, I have compiled a list of <a href="https://blog.finxter.com/how-real-freelancers-earn-money-in-2019-10-practical-python-projects/">10 suitable Python projects</a> (and published a blog article about that) which you can start doing today to improve your skill level and gain some confidence. Real freelancers have earned real money solving these projects — so they are as practical as they can be.</p>



<p>I recommend that you invest 70% of your learning time finishing these projects. First, you select the project. Second, you finish this project. No matter your current skill level. Even if you are a complete beginner then it will just take you weeks to finish the project which earned the freelancer 20 dollars. So what? Then you have worked weeks to earn $20 (which you would have invested for learning anyways) and you have improved your skill level a lot. But now you know you can solve the freelancer project.</p>



<p>The next projects will be much easier then. This time, it’ll take you not weeks but a week to finish a similar project. And the next project will take you only three days. And this is how your hourly rate increases exponentially in the beginning until you reach some convergence and your hourly rate flattens out. At this point, it’s important that you specialize even further. Select the skills that interest you and focus on those skills first. Always play your strengths.</p>



<p>If you need some more confidence then go read my <a href="https://blog.finxter.com/how-real-freelancers-earn-money-in-2019-10-practical-python-projects/">article about the 10 practical Python freelancer projects</a>, select one, and finish your first project yourself. This way, your learning will always be as practical as it can be.</p>



<p>If you want to know how much you can earn and get the overall picture of the state of Python freelancing in 2019, then check out my <a href="https://blog.finxter.com/webinar-freelancer/">free webinar</a>: How to earn $3000/M as a Python freelancer. It’ll take you only 30-40 minutes and I’ll explain you in detail the state of the art in freelancing, future outlooks and hot skills, and how much you can earn compared to employees and other professions.</p>



<p>As a <a href="https://www.quora.com/How-much-Python-HTML-CSS-and-JavaScript-do-I-need-to-learn-to-be-able-to-get-work-on-a-site-like-Freelancer-How-long-would-it-take-to-learn">Quora user</a> puts it: <em>“rank communication before development skills”</em>. It’s critical for your success that you develop these communication skills in a practical environment.</p>



<p><strong>Action step:</strong></p>



<ul class="wp-block-list">
<li>Take the first project you think you could solve. Then invest all your time and effort into cracking this project. Learn on the way. A sure way to improve and build a relationship with your clients &#8211; and make money in the process.</li>
</ul>



<h2 class="wp-block-heading" id="place-to-start">8. What is a Good Place to Start Python Freelancing?</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Start as a Freelance Developer Online? (Fiverr vs. Upwork vs. Own Consulting Website)" width="937" height="527" src="https://www.youtube.com/embed/m7RpKze1n4A?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>There are many different ways of starting your Python freelancing adventures. Many freelancing platforms compete for your time, attention, and a share of your value creation. These platforms are a great way to start your freelancing career as a Python coder and gain some experience in business and coding, as well as get some testimonial to kick off your freelancing business. But keep in mind that they are only the first step and in the mid-term, you should strive to become independent of those platforms if you want to avoid global competition for each project in the future.</p>



<p>So without further delay, these are the best places to start your Python freelancing career and get some clients fast (ordered by my recommendation):</p>



<h3 class="wp-block-heading"><a href="https://upwork.com">Upwork</a></h3>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="864" height="49" src="https://blog.finxter.com/wp-content/uploads/2019/08/grafik.png" alt="" class="wp-image-4188" srcset="https://blog.finxter.com/wp-content/uploads/2019/08/grafik.png 864w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-300x17.png 300w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-768x44.png 768w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-100x6.png 100w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-670x38.png 670w" sizes="auto, (max-width: 864px) 100vw, 864px" /></figure>



<p>Upwork places a great focus on quality. This is great for clients 
because it ensures that their work will get delivered—without 
compromising quality. </p>



<p>For freelancers just starting out, Upwork poses a significant barrier
 of entry—oftentimes, new profiles will get rejected by the Upwork team.
 They want to ensure that only clients who take their freelancing jobs 
seriously will start out on their platform.</p>



<p>However, the relatively high barrier of entry also protects 
established freelancers on the Upwork platform from too much 
competition. There is no price dumping because of low-quality offers 
which ultimately benefits all market participants.</p>



<h3 class="wp-block-heading"><a href="https://fiverr.com">Fiverr</a></h3>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="42" src="https://blog.finxter.com/wp-content/uploads/2019/08/grafik-1-1024x42.png" alt="" class="wp-image-4189" srcset="https://blog.finxter.com/wp-content/uploads/2019/08/grafik-1.png 1024w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-1-300x12.png 300w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-1-768x31.png 768w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-1-100x4.png 100w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-1-670x27.png 670w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Fiverr initially started out as a platform where you could buy and  sell small gigs worth five bucks. However, in the meantime, it grew to a full-fledged freelancing platform where people <a href="https://www.cnbc.com/2018/12/18/how-this-38-year-old-is-making-6-figures-freelancing-on-fiverr.html">earn six-figure incomes</a>. </p>



<p>Many jobs earn hundreds of dollars per hour and many freelancers make  a killing—especially in attractive industries such as programming,  machine learning, and data science.</p>



<p>If you want to start earning money as a freelance developer with the hot Python programming language, check out my free webinar:</p>



<p><a href="https://blog.finxter.com/webinar-freelancer/">How to build your high-income skill Python [Webinar]</a></p>



<h3 class="wp-block-heading"><a href="https://toptal.com">Toptal</a></h3>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="31" src="https://blog.finxter.com/wp-content/uploads/2019/08/grafik-2-1024x31.png" alt="" class="wp-image-4190" srcset="https://blog.finxter.com/wp-content/uploads/2019/08/grafik-2.png 1024w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-2-300x9.png 300w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-2-768x24.png 768w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-2-100x3.png 100w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-2-670x21.png 670w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Toptal has a strong market proposition: it’s the platform with the  top 3% of freelancers. Hence, it connects high-quality freelancers with high-quality clients. </p>



<p>It’s extremely hard to <a href="https://www.toptal.com/ultimate-freelancing-guide">become a freelancer at Toptal</a>: 97% of the  applicants will not enter the platform. However, if you manage to join Toptal, you can greatly benefit from the best-in-class hourly rates. You  can easily earn $100 per hour and beyond. </p>



<p>Also, the high barrier of entry ensures that the freelancer stays the
 valuable resource—he or she doesn’t become a commodity like on other 
freelancer platforms.</p>



<p>If you are an upcoming freelancer, you should aim for joining Toptal one day. <a href="https://blog.finxter.com/become-python-freelancer-course/">Here’s a great freelancer course</a> that shows you a crystal-clear path towards becoming a highly-paid freelancer. </p>



<h3 class="wp-block-heading"><a href="https://freelancer.com">Freelancer.com</a></h3>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="49" src="https://blog.finxter.com/wp-content/uploads/2019/08/grafik-3-1024x49.png" alt="" class="wp-image-4191" srcset="https://blog.finxter.com/wp-content/uploads/2019/08/grafik-3-1024x49.png 1024w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-3-300x14.png 300w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-3-768x37.png 768w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-3-100x5.png 100w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-3-670x32.png 670w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-3.png 1767w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Freelancer.com is the go-to resource for beginners with a very low barrier of entry and opportunities for everyone. This is the recommended  starting point to gain experience and finish your first projects. Also,  it can help you gain your first testimonials—while getting paid for  learning and polishing your skills.</p>



<p>It’s a great site with countless freelancing projects. A great resource is the <a href="https://www.freelancer.com/archives/">archived freelancing projects</a> which help you get some real-world projects for training purposes.</p>



<p>For freelance programmers, I have compiled a list of <a href="https://blog.finxter.com/how-real-freelancers-earn-money-in-2019-10-practical-python-projects/">ten practical freelancing projects</a>  to help you get started. These projects are real projects which were completed by real freelancers for real money. So they are as practical as they can get.</p>



<hr class="wp-block-separator has-css-opacity"/>



<p>Of course, there are a lot more general freelancing websites. I will list a few of them in the following:</p>



<ul class="wp-block-list">
<li><a href="https://www.peopleperhour.com/">https://www.peopleperhour.com/</a></li>



<li><a href="https://remote.com/">https://remote.com/</a></li>



<li><a href="https://www.guru.com/">https://www.guru.com/</a></li>



<li><a href="https://www.truelancer.com/">https://www.truelancer.com/</a></li>
</ul>



<p>Also, if you are looking for specialized freelancing platforms, you 
should look a bit further. For example, an excellent way of offering 
your writing services is:</p>



<h3 class="wp-block-heading"><a href="https://www.iwriter.com/">iWrite</a><a href="https://www.iwriter.com/">r</a></h3>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="406" src="https://blog.finxter.com/wp-content/uploads/2019/08/grafik-4-1024x406.png" alt="" class="wp-image-4194" srcset="https://blog.finxter.com/wp-content/uploads/2019/08/grafik-4.png 1024w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-4-300x119.png 300w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-4-768x305.png 768w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-4-100x40.png 100w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-4-670x266.png 670w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>The best site for offering your programming services is:</p>



<h3 class="wp-block-heading"><a href="https://www.twago.com/">Twago</a></h3>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="410" src="https://blog.finxter.com/wp-content/uploads/2019/08/grafik-6-1024x410.png" alt="" class="wp-image-4196" srcset="https://blog.finxter.com/wp-content/uploads/2019/08/grafik-6.png 1024w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-6-300x120.png 300w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-6-768x308.png 768w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-6-100x40.png 100w, https://blog.finxter.com/wp-content/uploads/2019/08/grafik-6-670x269.png 670w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>However, the general freelancing sites such as Upwork, Toptal, and Fiverr are good enough for most cases. To learn more about the best Python freelancer sites, check out <a href="https://blog.finxter.com/what-are-the-best-freelancing-sites/">my original blog article</a>.</p>



<p><strong>Action step:</strong></p>



<ul class="wp-block-list">
<li>Before you move on, decide for one platform (my personal recommendation: Upwork &#8212; and, no, I&#8217;m not affiliated with any institution) and stick for it for at least one year. Commitment is king!</li>
</ul>



<h2 class="wp-block-heading">More Finxter Tutorials</h2>



<p>Learning is a continuous process and you&#8217;d be wise to <a rel="noreferrer noopener" href="https://blog.finxter.com/start-learning-python/" data-type="post" data-id="841" target="_blank">never stop learning</a> and improving throughout your life. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f451.png" alt="👑" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p><strong>What to learn?</strong> Your subconsciousness often knows better than your conscious mind what skills you need to <strong>reach the next level of success</strong>.</p>



<p>I recommend you read at least <strong>one tutorial per day</strong> (only 5 minutes per tutorial is enough) to make sure you never stop learning! </p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> If you want to make sure you don&#8217;t forget your habit, feel free to join our <a rel="noreferrer noopener" href="https://blog.finxter.com/email-academy/" data-type="URL" data-id="https://blog.finxter.com/email-academy/" target="_blank">free email academy</a> for weekly fresh tutorials and learning reminders in your INBOX. </p>



<p>Also, skim the following list of tutorials and open 3 interesting ones in a new browser tab to start your new &#8212; or continue with your existing &#8212; learning habit today! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p><strong>Python Basics:</strong></p>



<ul class="wp-block-list"><li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" target="_blank">Python One Line For Loop</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-how-to-import-modules-from-another-folder/" target="_blank">Import Modules From Another Folder</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-determine-the-type-of-an-object-in-python/" target="_blank">Determine Type of Python Object</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-convert-a-string-list-to-an-integer-list-in-python/" target="_blank">Convert String List to Int List</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-convert-an-integer-list-to-a-string-list-in-python/" target="_blank">Convert Int List to String List</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-convert-a-string-list-to-a-float-list-in-python/" target="_blank">Convert String List to Float List</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-check-python-version-in-jupyter-notebook/" target="_blank">Convert List to NumPy Array</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-append-data-to-a-json-file-in-python/" target="_blank">Append Data to JSON File</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-filter-a-list-in-python/" target="_blank">Filter List Python</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-of-lists/" target="_blank">Nested List</a></li></ul>



<p><strong>Python Dependency Management:</strong></p>



<ul class="wp-block-list"><li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-install-pil/" target="_blank">Install PIP</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-check-your-python-version/" target="_blank">How to Check Your Python Version</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-check-the-pandas-version-in-your-script/" target="_blank">Check Pandas Version in Script</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-check-python-version-in-jupyter-notebook/" target="_blank">Check Python Version Jupyter</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-check-version-of-package-with-pip/" target="_blank">Check Version of Package PIP</a></li></ul>



<p><strong>Python Debugging:</strong></p>



<ul class="wp-block-list"><li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-catch-and-print-exception-messages-in-python/" target="_blank">Catch and Print Exceptions</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-indexerror-list-index-out-of-range/" target="_blank">List Index Out Of Range</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-fix-valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous-use-a-any-or-a-all/" target="_blank">Fix Value Error Truth</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-fix-importerror-cannot-import-name-x-in-python/" target="_blank">Cannot Import Name X Error</a></li></ul>



<p><strong>Fun Stuff:</strong></p>



<ul class="wp-block-list"><li><a href="https://blog.finxter.com/collection-5-cheat-sheets-every-python-coder-must-own/" data-type="URL" data-id="https://blog.finxter.com/collection-5-cheat-sheets-every-python-coder-must-own/" target="_blank" rel="noreferrer noopener">5 Cheat Sheets Every Python Coder Needs to Own</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/10-best-python-puzzles-to-discover-your-true-skill-level/" data-type="URL" data-id="https://blog.finxter.com/10-best-python-puzzles-to-discover-your-true-skill-level/" target="_blank">10 Best Python Puzzles to Discover Your True Skill Level</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-earn-1000-on-the-side-as-a-python-freelancer-a-step-by-step-tutorial/" data-type="URL" data-id="https://blog.finxter.com/how-to-earn-1000-on-the-side-as-a-python-freelancer-a-step-by-step-tutorial/" target="_blank">How to $1000 on the Side as a Python Freelancer</a></li></ul>



<p>Thanks for learning with Finxter!</p>






<p></p>
<p>The post <a href="https://blog.finxter.com/how-to-earn-1000-on-the-side-as-a-python-freelancer-a-step-by-step-tutorial/">How to Become a Python Freelancer&#8212;and Earn $1,000 on the Side? [A Step-by-Step Tutorial]</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python Dictionary &#8211; The Ultimate Guide</title>
		<link>https://blog.finxter.com/python-dictionary/</link>
		
		<dc:creator><![CDATA[Adam Murphy]]></dc:creator>
		<pubDate>Mon, 10 Aug 2020 19:58:00 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Dictionary]]></category>
		<category><![CDATA[Python 3]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=5232</guid>

					<description><![CDATA[<p>Python comes with several built-in data types. These are the foundational building blocks of the whole language. They have been optimised and perfected over many years. In this comprehensive tutorial, we will explore one of the most important: the dictionary (or dict for short). For your convenience, I&#8217;ve created a comprehensive 8000-word eBook which you ... <a title="Python Dictionary &#8211; The Ultimate Guide" class="read-more" href="https://blog.finxter.com/python-dictionary/" aria-label="Read more about Python Dictionary &#8211; The Ultimate Guide">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-dictionary/">Python Dictionary &#8211; The Ultimate Guide</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Python comes with several built-in data types. These are the foundational building blocks of the whole language. They have been optimised and perfected over many years. In this comprehensive tutorial, we will explore one of the most important: the dictionary (or dict for short).</p>



<p>For your convenience, I&#8217;ve created a comprehensive 8000-word eBook which you can <a href="https://drive.google.com/file/d/1k0Wlj5tLT8SGf3hVrJgJaqXP20FsNAA5/view?usp=sharing" target="_blank" rel="noreferrer noopener" title="https://drive.google.com/file/d/1k0Wlj5tLT8SGf3hVrJgJaqXP20FsNAA5/view?usp=sharing">download directly as a high-resolution PDF</a> (opens in a new window).</p>



<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link has-black-color has-pale-cyan-blue-background-color has-text-color has-background" href="https://drive.google.com/file/d/1k0Wlj5tLT8SGf3hVrJgJaqXP20FsNAA5/view?usp=sharing" target="_blank" rel="noreferrer noopener">Download Article as PDF</a></div>
</div>



<div style="height:74px" aria-hidden="true" class="wp-block-spacer"></div>



<p>Unless stated otherwise I will be using Python 3.8 throughout. Dictionary functionality has changed over the last few Python versions. If you are using a version other than 3.8, you will probably get different results.</p>



<p>To <a href="https://blog.finxter.com/how-to-check-your-python-version/" target="_blank" rel="noreferrer noopener">check what version of Python</a> you are running, enter the following in a terminal window (mine returns 3.8).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ python --version
Python 3.8.0</pre>



<p>Here&#8217;s a minimal example that shows how to use a dictionary in an interactive Python shell. Feel free to play around!</p>



<iframe loading="lazy" src="https://trinket.io/embed/python/27952386c5" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="500" frameborder="0"></iframe>



<p><em><strong>Exercise</strong>: Add 2 apples and 3 oranges to your basket of fruits! How many fruits are in your basket?</em></p>



<h2 class="wp-block-heading">Python Dictionary Video Tutorial</h2>



<p>Don&#8217;t want to read the article? No problem, watch me going over the article:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Dictionary – The Ultimate Guide" width="937" height="527" src="https://www.youtube.com/embed/qX0qqEVpP5s?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Here&#8217;s the link to the <a href="https://www.digistore24.com/redir/261950/adsmurphy/" target="_blank" rel="noreferrer noopener">Python freelancer course</a> in case you want to start being your own boss with Python.</p>



<h2 class="wp-block-heading">Python Dictionary &#8211; Why Is It So Useful? </h2>



<p>When I first found out about dictionaries, I wasn&#8217;t sure if they were going to be very useful. They seemed a bit clunky and I felt like lists would be much more useful. But boy was I wrong!</p>



<p>In real life, a dictionary is a book full of words in alphabetical order. Beside each word is a definition. If it has many meanings, there are many definitions. Each word appears exactly once.</p>



<ul class="wp-block-list"><li>A book of words in alphabetical order.</li><li>Each word has an associated definition</li><li>If a word has many meanings, it has many definitions</li><li>As time changes, more meanings can be added to a word.</li><li>The spelling of a word never changes.</li><li>Each word appears exactly once.</li><li>Some words have the same definition.</li></ul>



<p>If we abstract this idea, we can view a dictionary as a mapping from a word to its definition. Making this more abstract, a dictionary is a mapping from something we know (a word) to something we don&#8217;t (its definition).&nbsp;</p>



<p>We apply this mapping all the time in real life:&nbsp;In our phone, we map our friends&#8217; names to their phone numbers.</p>



<p>In our minds, we map a person&#8217;s name to their face.</p>



<p>We map words to their meaning.</p>



<p>This &#8216;mapping&#8217; is really easy for humans to understand and makes life much more efficient. We do it all the time without even realising. Thus it makes sense for Python to include this as a foundational data type.&nbsp;</p>



<h2 class="wp-block-heading">Python Dictionary Structure</h2>



<p>A traditional dictionary maps words to definitions. Python dictionaries can contain any data type, so we say they map keys to values. Each is called a key-value pair.</p>



<p>The key &#8216;unlocks&#8217; the value. A key should be easy to remember and not change over time. The value can be more complicated and may change over time.</p>



<p>We will now express the same list as above using Python dictionary terminology.</p>



<ul class="wp-block-list"><li>Python dictionary is a collection of <a href="https://blog.finxter.com/object-oriented-programming-terminology-cheat-sheet/">objects</a> (keys and values)</li><li>Each key has an associated value</li><li>A key can have many values</li><li>As time changes, more values can be added to a key (values are mutable)</li><li>A key cannot change (keys are immutable)</li><li>Each key appears exactly once</li><li>Keys can have the same value</li></ul>



<p><em><strong>Note</strong>: we can order dictionaries if we want but it is not necessary to do so. We&#8217;ll explain all these concepts in more detail throughout the article. But before we do anything, we need to know how to create a dictionary!</em></p>



<h2 class="wp-block-heading">Python Create Dictionary</h2>



<p>There are two ways to create a dictionary in Python:</p>



<ol class="wp-block-list"><li>Curly braces <code>{ }</code></li><li>The <code>dict()</code> constructor</li></ol>



<h3 class="wp-block-heading">Curly Braces { }</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_dict = {key1: value1,
           key2: value2,
           key3: value3,
           key4: value4,
           key5: value5}</pre>



<p>We write the key, immediately followed by a colon. Then a single space, the value and finally a comma. After the last pair, replace the comma with a closing curly brace. </p>



<p>You can write all pairs on the same line. I put each on a separate line to aid readability. </p>



<p>Let&#8217;s say you have 5 friends and want to record which country they are from. You would write it like so (names and countries start with the same letter to make them easy to remember!).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">names_and_countries = {'Adam': 'Argentina',
                       'Beth': 'Bulgaria',
                       'Charlie': 'Colombia',
                       'Dani': 'Denmark',
                       'Ethan': 'Estonia'}</pre>



<h3 class="wp-block-heading">The dict() Constructor</h3>



<h4 class="wp-block-heading"><em>Option 1 &#8211; fastest to type</em></h4>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_dict = dict(key1=value1,
               key2=value2,
               key3=value3,
               key4=value4,
               key5=value5)</pre>



<p>So names_and_countries becomes</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">names_and_countries = dict(Adam='Argentina',
                           Beth='Bulgaria',
                           Charlie='Colombia',
                           Dani='Denmark',
                           Ethan='Estonia')</pre>



<p>Each pair is like a <a href="https://blog.finxter.com/daily-python-puzzle-arbitrary-argument-listsstring-concatenation-join-function/" target="_blank" rel="noreferrer noopener" title="Arbitrary Argument Lists, String Concatenation, and the Join Function in Python">keyword argument</a> in a function. Keys are automatically converted to strings but values must be typed as strings. </p>



<h4 class="wp-block-heading"><em>Option 2 &#8211; slowest to type, best used with zip()</em></h4>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_dict = dict([(key1, value1),
                (key2, value2),
                (key3, value3),
                (key4, value4),
                (key5, value5)])</pre>



<p><code>names_and_countries</code> becomes</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">names_and_countries = dict([('Adam', 'Argentina'),
                            ('Beth', 'Bulgaria'),
                            ('Charlie', 'Colombia'),
                            ('Dani', 'Denmark'),
                            ('Ethan', 'Estonia')])</pre>



<p>Like with curly braces, we must explicitly type strings as strings. If you forget the quotes, Python interprets it as a function.</p>



<h4 class="wp-block-heading"><em>Option 2 with zip() &#8211; Python list to dict</em></h4>



<p>If you have two <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">lists </a>and want to make a dictionary from them, do this</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">names = ['Adam', 'Beth', 'Charlie', 'Dani', 'Ethan']
countries = ['Argentina', 'Bulgaria', 'Colombia', 'Denmark', 'Estonia']
 
# Keys are names, values are countries
names_and_countries = dict(zip(names, countries))
 
>>> names_and_countries
{'Adam': 'Argentina',
'Beth': 'Bulgaria',
'Charlie': 'Colombia',
'Dani': 'Denmark',
'Ethan': 'Estonia'}</pre>



<p>If you have more than two lists, do this</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">names = ['Adam', 'Beth', 'Charlie', 'Dani', 'Ethan']
countries = ['Argentina', 'Bulgaria', 'Colombia', 'Denmark', 'Estonia']
ages = [11, 24, 37, 75, 99]
 
# Zip all values together
values = zip(countries, ages)
 
# Keys are names, values are the tuple (countries, ages)
people_info = dict(zip(names, values))
 
>>> people_info
{'Adam': ('Argentina', 11),
'Beth': ('Bulgaria', 24),
'Charlie': ('Colombia', 37),
'Dani': ('Denmark', 75),
'Ethan': ('Estonia', 99)}</pre>



<p>This is the first time we&#8217;ve seen a dictionary containing more than just strings! We&#8217;ll soon find out what can and cannot be a key or value. But first, let&#8217;s see how to access our data.</p>



<h2 class="wp-block-heading">Accessing Key-Value Pairs</h2>



<p>There are 2 ways to access the data in our dictionaries:</p>



<ul class="wp-block-list"><li>Bracket notation [ ]</li><li>The get() method</li></ul>



<h3 class="wp-block-heading">Bracket Notation [ ]</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Get value for the key 'Adam'
>>> names_and_countries['Adam']
'Argentina'
 
# Get value for the key 'Charlie'
>>> names_and_countries['Charlie']
'Colombia'
 
# KeyError if you search for a key not in the dictionary
>>> names_and_countries['Zoe']
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
KeyError: 'Zoe'</pre>



<p>Type the key into the square brackets to get the corresponding value. If you enter a key not in the dictionary, Python raises a <code>KeyError</code>. </p>



<p>This looks like list indexing but it is completely different! For instance, you cannot access values by their relative position or by <a href="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank" rel="noreferrer noopener" title="Introduction to Slicing in Python">slicing</a>. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Not the first element of the dictionary
>>> names_and_countries[0]
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
KeyError: 0
 
# Not the last element
>>> names_and_countries[-1]
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
KeyError: -1
 
# You cannot slice
>>> names_and_countries['Adam':'Dani']
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
TypeError: unhashable type: 'slice'</pre>



<p>Python expects everything between the brackets to be a key. So for the first two examples, we have a <code>KeyError</code> because neither 0 nor -1 are keys in the dictionary. But is possible to use 0 or -1 as a key, as we will see soon.</p>



<p>Note: As of Python 3.7, the order elements are added is preserved. Yet you cannot use this order to access elements. It is more for iteration and visual purposes as we will see later. </p>



<p>If we try to slice our dictionary, Python raises a <code>TypeError</code>. We explain why in the Hashing section.</p>



<p>Let&#8217;s look at the second method for accessing the data stored in our dictionary.</p>



<h3 class="wp-block-heading">Python Dictionary get() Method</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Get value for the key 'Adam'
>>> names_and_countries.get('Adam')
'Argentina'
 
# Returns None if key not in the dictionary
>>> names_and_countries.get('Zoe')
 
# Second argument returned if key not in dictionary
>>> names_and_countries.get('Zoe', 'Name not in dictionary')
'Name not in dictionary'
 
# Returns value if key in dictionary
>>> names_and_countries.get('Charlie', 'Name not in dictionary')
'Colombia'</pre>



<p>The <code>get()</code> method takes two arguments:</p>



<ol class="wp-block-list"><li>The key you wish to search for</li><li>(optional) Value to return if the key is not in the dictionary (default is None).</li></ol>



<p>It works like bracket notation. But it will never raise a <code>KeyError</code>. Instead, it returns either None or the object you input as the second argument. </p>



<p>This is hugely beneficial if you are iterating over a dictionary. If you use bracket notation and encounter an error, the whole iteration will stop. If you use get(), no error will be raised and the iteration will complete. </p>



<p>We will see how to iterate over dictionaries soon. But there is no point in doing that if we don&#8217;t even know what our dictionary can contain! Let&#8217;s learn about what can and can&#8217;t be a key-value pair. </p>



<h2 class="wp-block-heading">Python Dict Keys</h2>



<p>In real dictionaries, the spelling of words doesn&#8217;t change. It would make it quite difficult to use one if they did. The same applies to Python dictionaries. Keys cannot change. But they can be more than just strings. In fact, keys can be any immutable data type: string, int, float, bool or <a href="https://blog.finxter.com/python-tuple-to-integer/" title="Python Tuple to Integer">tuple</a>. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> string_dict = {'hi': 'hello'}
>>> int_dict = {1: 'hello'}
>>> float_dict = {1.0: 'hello'}
>>> bool_dict = {True: 'hello', False: 'goodbye'}
>>> tuple_dict = {(1, 2): 'hello'}
 
# Tuples must only contain immutable types
>>> bad_tuple_dict = {(1, [2, 3]): 'hello'}
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
TypeError: unhashable type: 'list'</pre>



<p>This is the second time we&#8217;ve seen <code>"TypeError: unhashable type: 'list'"</code>. So what does &#8216;unhashable&#8217; mean?&nbsp;</p>



<h2 class="wp-block-heading">What is Hashing in Python?</h2>



<p>In the background, a Python dictionary is a data structure known as a<a href="https://en.wikipedia.org/wiki/Hash_function"> hash table</a>. It contains keys and hash values (numbers of fixed length). You apply <code>hash()</code> to a key to return its hash value. If we call <code>hash()</code> on the same key many times, the result will not change. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Python 3.8 (different versions may give different results)
>>> hash('hello world!')
1357213595066920515
 
# Same result as above
>>> hash('hello world!')
1357213595066920515
 
# If we change the object, we change the hash value
>>> hash('goodbye world!')
-7802652278768862152</pre>



<p>When we create a key-value pair, Python creates a hash-value pair in the background</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># We write
>>> {'hello world!': 1}
 
# Python executes in the background
>>> {hash('hello world!'): 1}
 
# This is equivalent to
>>> {1357213595066920515: 1}</pre>



<p>Python uses this hash value when we look up a key-value pair. By design, the hash function can only be applied to immutable data types. If keys could change, Python would have to create a new hash table from scratch every time you change them. This would cause huge inefficiencies and many bugs. </p>



<p>Instead, once a table is created, the hash value cannot change. Python knows which values are in the table and doesn&#8217;t need to calculate them again. This makes dictionary lookup and membership operations instantaneous and of <a href="https://blog.finxter.com/complexity-of-python-operations/" target="_blank" rel="noreferrer noopener" title="Complexity of Python Operations">O(1)</a>. </p>



<p>In Python, the concept of hashing only comes up when discussing dictionaries. Whereas, mutable vs immutable data types come up everywhere. Thus we say that you can only use immutable data types as keys, rather than saying &#8216;hashable&#8217; data types. </p>



<p>Finally, what happens if you use the hash value of an object as another key in the same dictionary? Does Python get confused?</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> does_this_work = {'hello': 1,
   			   hash('hello'): 2}
 
>>> does_this_work['hello']
1
 
>>> does_this_work[hash('hello')]
2</pre>



<p>It works! The reasons why are beyond the scope of this article. The full implementation of the algorithm and the reasons why it works are described<a href="https://hg.python.org/cpython/file/default/Objects/dictobject.c"> here</a>. All you really need to know is that Python always picks the correct value&#8230; even if you try to confuse it!&nbsp;</p>



<h2 class="wp-block-heading">Python Dictionary Values</h2>



<p>There are restrictions on dictionary keys but values have none. Literally anything can be a value. As long as your key is an immutable data type, your key-value pairs can be any combination of types you want. You have complete control!</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> crazy_dict = {11.0: ('foo', 'bar'),
                  'baz': {1: 'a', 2: 'b'},
                  (42, 55): {10, 20, 30},
                  True: False}
 
# Value of the float 11.0 is a tuple
>>> crazy_dict[11.0]
('foo', 'bar')
 
# Value of the string 'baz' is a dictionary
>>> crazy_dict.get('baz')
{1: 'a', 2: 'b'}
 
# Value of the tuple (42, 55) is a set
>>> crazy_dict[(42, 55)]
{10, 20, 30}
 
# Value of the Bool True is the Bool False
>>> crazy_dict.get(True)
False</pre>



<p><em><strong>Note</strong>: you must use braces notation to type a dictionary out like this. If you try to use the <code>dict()</code> constructor, you will get SyntaxErrors (unless you use the verbose method and type out a list of tuples&#8230; but why would you do that?).</em></p>



<p>If you need to refresh your basic knowledge of Python sets, I recommend reading <a href="https://blog.finxter.com/sets-in-python/">the ultimate guide to Python sets</a> on the Finxter blog.</p>



<h2 class="wp-block-heading">Python Nested Dictionaries</h2>



<p>When <a href="https://blog.finxter.com/full-time-python-freelancer/" target="_blank" rel="noreferrer noopener" title="How to Go Full-Time ($3000/m) as a Python Freelancer﻿">web scraping</a>, it is very common to work with dictionaries inside dictionaries (nested dictionaries). To access values on deeper levels, you simply chain methods together. Any order of bracket notation and <code>get()</code> is possible.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Returns a dict
>>> crazy_dict.get('baz')
{1: 'a', 2: 'b'}
 
# Chain another method to access the values of this dict
>>> crazy_dict.get('baz').get(1)
'a'
 
>>> crazy_dict.get('baz')[2]
'b'</pre>



<p>We now know how to create a dictionary and what data types are allowed where. But what if you&#8217;ve already created a dictionary and want to add more values to it?&nbsp;</p>



<h2 class="wp-block-heading">Python Add To Dictionary</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> names_and_countries
{'Adam': 'Argentina', 
'Beth': 'Bulgaria', 
'Charlie': 'Colombia', 
'Dani': 'Denmark', 
'Ethan': 'Estonia'}
 
# Add key-value pair 'Zoe': 'Zimbabwe'
>>> names_and_countries['Zoe'] = 'Zimbabwe'
 
# Add key-value pair 'Fred': 'France'
>>> names_and_countries['Fred'] = 'France'
 
# Print updated dict
>>> names_and_countries
{'Adam': 'Argentina', 
'Beth': 'Bulgaria', 
'Charlie': 'Colombia', 
'Dani': 'Denmark', 
'Ethan': 'Estonia', 
'Zoe': 'Zimbabwe',     # Zoe first
'Fred': 'France'}      # Fred afterwards</pre>



<p>Our dictionary reflects the order we added the pairs by first showing Zoe and then Fred. </p>



<p>To add a new key-value pair, we simply assume that key already exists and try to access it via bracket notation</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> my_dict['new_key']</pre>



<p>Then (before pressing return) use the assignment operator &#8216;=&#8217;&nbsp; and provide a value.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> my_dict['new_key'] = 'new_value'</pre>



<p>You cannot assign new key-value pairs via the <code>get()</code> method because it&#8217;s a function call.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> names_and_countries.get('Holly') = 'Hungary'
File "&lt;stdin>", line 1
SyntaxError: cannot assign to function call</pre>



<p>To delete a key-value pair use the <code><a href="https://blog.finxter.com/the-most-pythonic-way-to-remove-multiple-items-from-a-list/" title="The Most Pythonic Way to Remove Multiple Items From a List">del</a></code> statement. To change the value of an existing key, use the same bracket notation as above. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Delete the Zoe entry
>>> del names_and_countries['Zoe']
 
# Change Ethan's value
>>> names_and_countries['Ethan'] = 'DIFFERENT_COUNTRY'
 
>>> names_and_countries
{'Adam': 'Argentina', 
'Beth': 'Bulgaria', 
'Charlie': 'Colombia', 
'Dani': 'Denmark', 
'Ethan': 'DIFFERENT_COUNTRY',  # Ethan has changed
'Fred': 'France'}    		  # We no longer have Zoe</pre>



<p>As with other mutable data types, be careful when using the <code>del</code> statement in a <a href="https://blog.finxter.com/python-loops/" title="Python Loops" target="_blank" rel="noreferrer noopener">loop</a>. It modifies the dictionary in place and can lead to unintended consequences. Best practice is to create a copy of the dictionary and to change the copy. Or you can use, my personal favorite, <strong>dictionary comprehensions</strong> (which we will cover later)&#8212;a powerful feature similar to the popular <a href="https://blog.finxter.com/list-comprehension/">list comprehension feature in Python</a>.</p>



<h2 class="wp-block-heading">Python Dict Copy Method</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> my_dict = {'a': 1, 'b': 2}
 
# Create a shallow copy
>>> shallow_copy = my_dict.copy()
 
# Create a deep copy
>>> import copy
>>> deep_copy = copy.deepcopy(my_dict)</pre>



<p>To create a shallow copy of a dictionary use the <code><a href="https://blog.finxter.com/python-list-copy/" title="Python List copy()">copy()</a></code> method. To create a deep copy use the <code>deepcopy()</code> method from the built-in copy module. We won&#8217;t discuss the distinction between the copy methods in this article for brevity.</p>



<h2 class="wp-block-heading">Checking Dictionary Membership</h2>



<p>Let&#8217;s say we have a dictionary with 100k key-value pairs. We cannot print it to the screen and visually check which key-value pairs it contains. </p>



<p>Thankfully, the following syntax is the same for dictionaries as it is for other objects such as lists and sets. We use the <code>in</code> keyword.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Name obviously not in our dict
>>> 'INCORRECT_NAME' in names_and_countries
False
 
# We know this is in our dict
>>> 'Adam' in names_and_countries
True
 
# Adam's value is in the dict... right?
>>> names_and_countries['Adam']
'Argentina'
>>> 'Argentina' in names_and_countries
False</pre>



<p>We expect INCORRECT_NAME not to be in our dict and Adam to be in it. But why does &#8216;Argentina&#8217; return False? We&#8217;ve just seen that it&#8217;s the value of Adam?!</p>



<p>Remember at the start of the article that I said dictionaries are maps? They map from something we know (the key) to something we don&#8217;t (the value). So when we ask if something is in our dictionary, we are asking if it is a key. We&#8217;re not asking if it&#8217;s a value. </p>



<p>Which is more natural when thinking of a real-life dictionary:</p>



<ol class="wp-block-list"><li>Is the word &#8216;facetious&#8217; in this dictionary?</li><li>Is the word meaning &#8216;lacking serious intent; concerned with something nonessential, amusing or frivolous&#8217; in<a href="https://www.dictionary.com/browse/facetious?s=t"> this</a> dictionary?</li></ol>



<p>Clearly the first one is the winner and this is the default behavior for Python.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 'something' in my_dict</pre>



<p>We are checking if &#8216;something&#8217; is a <em>key</em> in my_dict.</p>



<p>But fear not, if you want to check whether a specific value is in a dictionary, that is possible! We simply have to use some methods.&nbsp;</p>



<h2 class="wp-block-heading">Python Dictionary Methods &#8211; Keys, Values and Items</h2>



<p>There are 3 methods to look at. All can be used to check membership or for iterating over specific parts of a dictionary. Each returns an iterable.</p>



<ul class="wp-block-list"><li>.keys() &#8211; iterate over the dictionary&#8217;s keys</li><li>.values() &#8211; iterate over the dictionary&#8217;s values</li><li>.items() &#8211; iterate over both the dictionary&#8217;s keys and values</li></ul>



<p>Note: we&#8217;ve changed Ethan&#8217;s country back to Estonia for readability.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> names_and_countries.keys()
dict_keys(['Adam', 'Beth', 'Charlie', 'Dani', 'Ethan', 'Fred'])
 
>>> names_and_countries.values()
dict_values(['Argentina', 'Bulgaria', 'Colombia', 'Denmark', 'Estonia', 'France'])
 
>>> names_and_countries.items()
 
 
dict_items([('Adam', 'Argentina'), 
            ('Beth', 'Bulgaria'), 
            ('Charlie', 'Colombia'), 
            ('Dani', 'Denmark'), 
            ('Ethan', 'Estonia'), 
            ('Fred', 'France')])</pre>



<p>We can now check membership in keys and values:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Check membership in dict's keys
>>> 'Adam' in names_and_countries
True
>>> 'Adam' in names_and_countries.keys()
True
 
# Check membership in the dict's values
>>> 'Argentina' in names_and_countries.values()
True
 
# Check membership in either keys or values???
>>> 'Denmark' in names_and_countries.items()
False</pre>



<p>You cannot check in the keys and values at the same time. This is because <code>items()</code> returns an iterable of tuples. As <code>'Denmark'</code> is not a tuple, it will return False. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> for thing in names_and_countries.items():
  	  print(thing)
('Adam', 'Argentina')
('Beth', 'Bulgaria')
('Charlie', 'Colombia')
('Dani', 'Denmark')
('Ethan', 'Estonia')
 
# True because it's a tuple containing a key-value pair
>>> ('Dani', 'Denmark') in names_and_countries.items()
True</pre>



<h2 class="wp-block-heading">Python Loop Through Dictionary &#8211; An Overview</h2>



<p>To iterate over any part of the dictionary we can use a <a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" target="_blank" rel="noreferrer noopener" title="Python One Line For Loop [A Simple Tutorial]">for loop</a></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> for name in names_and_countries.keys():
        print(name)
Adam
Beth
Charlie
Dani
Ethan
Fred
 
>>> for country in names_and_countries.values():
        print(f'{country} is wonderful!')
Argentina is wonderful!
Bulgaria is wonderful!
Colombia is wonderful!
Denmark is wonderful!
Estonia is wonderful!
France is wonderful!
 
>>> for name, country in names_and_countries.items():
        print(f'{name} is from {country}.')
Adam is from Argentina.
Beth is from Bulgaria.
Charlie is from Colombia.
Dani is from Denmark.
Ethan is from Estonia.
Fred is from France.</pre>



<p>It&#8217;s best practice to use descriptive names for the objects you iterate over. Code is meant to be read and understood by humans! Thus we chose &#8216;name&#8217; and &#8216;country&#8217; rather than &#8216;key&#8217; and &#8216;value&#8217;. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Best practice
>>> for descriptive_key, descriptive_value in my_dict.items():
        # do something
 
# Bad practice (but you will see it 'in the wild'!)
>>> for key, value in my_dict.items():
        # do something</pre>



<p>If your key-value pairs don&#8217;t follow a specific pattern, it&#8217;s ok to use &#8216;key&#8217; and &#8216;value&#8217; as your iterable variables, or even &#8216;k&#8217; and &#8216;v&#8217;.  </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Iterating over the dict is the same as dict.keys()
>>> for thing in names_and_countries:
        print(thing)
Adam
Beth
Charlie
Dani
Ethan
Fred</pre>



<h2 class="wp-block-heading">A Note On Reusability</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Works with general Python types
>>> for key in object:
        # do something
 
# Works only with dictionaries
>>> for key in object.keys():
        # do something</pre>



<p>Do not specify keys() if your code needs to work with other objects like lists and sets. Use the keys() method if your code is only meant for dictionaries. This prevents future users inputting incorrect objects. </p>



<h2 class="wp-block-heading">Python dict has_key</h2>



<p>The method has_key() is exclusive to Python 2. It returns True if the key is in the dictionary and False if not. </p>



<p>Python 3 removed this functionality in favour of the following syntax:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> if key in d:
        # do something</pre>



<p>This keeps dictionary syntax in line with that of other data types such as sets and lists. This aids readability and reusability. </p>



<h2 class="wp-block-heading">Pretty Printing Dictionaries Using pprint()</h2>



<p>The built-in module pprint contains the function pprint. This will &#8216;pretty print&#8217; your dictionary. It sorts the keys alphabetically and <a href="https://blog.finxter.com/the-separator-and-end-arguments-of-the-python-print-function/" target="_blank" rel="noreferrer noopener" title="Python Print Function [And Its SECRET Separator &amp; End Arguments]">prints </a>each key-value pair on a newline. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> from pprint import pprint
>>> messy_dict = dict(z='Here is a really long key that spans a lot of text', a='here is another long key that is really too long', j='this is the final key in this dictionary')
 
>>> pprint(messy_dict)
{'a': 'here is another long key that is really too long',
'j': 'this is the final key in this dictionary',
'z': 'Here is a really long key that spans a lot of text'}</pre>



<p>It does not change the dictionary at all. It&#8217;s just much more readable now. </p>



<h2 class="wp-block-heading">Python Dictionaries and JSON Files</h2>



<p><em>We need to encode and decode all this data</em>.</p>



<p>A common filetype you will interact with is a JSON file. It stands for Javascript Object Notation. They are used to structure and send data in web applications. </p>



<p>They work almost exactly the same way as dictionaries and you can easily turn one into the other very easily. </p>



<h3 class="wp-block-heading">Python Dict to JSON</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import json
>>> my_dict = dict(a=1, b=2, c=3, d=4)
 
>>> with open('my_json.json', 'w') as f:
   	 json.dump(my_dict, f)</pre>



<p>The above code takes <code>my_dict</code> and writes it to the file <code>my_json.json</code> in the current directory. </p>



<p>You can get more complex than this by setting character encodings and spaces. For more detail, we direct the reader to<a href="https://docs.python.org/3.8/library/json.html"> the docs</a>. </p>



<h3 class="wp-block-heading">Python JSON to Dict</h3>



<p>We have the file <code>my_json.json</code> in our current working directory. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import json
>>> with open('my_json.json', 'r') as f:
        new_dict = json.load(f)
 
>>> new_dict
{'a': 1, 'b': 2, 'c': 3, 'd': 4}</pre>



<p><em><strong>Note</strong>: the key-value pairs in JSON are always converted to strings when encoded in Python. It is easy to change any object into a string and it leads to fewer errors when encoding and decoding files. But it means that sometimes the file you load and the file you started with are not identical.&nbsp; </em></p>



<h2 class="wp-block-heading">Python Dictionary Methods</h2>



<p>Here&#8217;s a quick overview:</p>



<ol class="wp-block-list"><li>dict.clear() &#8211; remove all key-value pairs from a dict</li><li>dict.update() &#8211; merge two dictionaries together</li><li>dict.pop() &#8211; remove a key and return its value</li><li>dict.popitem() &#8211; remove a random key-value pair and return it as a tuple</li></ol>



<p>We&#8217;ll use letters A and B for our dictionaries as they are easier to read than descriptive names. Plus we have kept the examples simple to aid understanding. </p>



<h3 class="wp-block-heading">dict.clear() &#8211; remove all key-value pairs from a dict</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> A = dict(a=1, b=2)
>>> A.clear()
>>> A
{}</pre>



<p>Calling this on a dict removes all key-value pairs in place. The dict is now empty. </p>



<h3 class="wp-block-heading">dict.update() &#8211; merge two dictionaries together</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> A = dict(a=1, b=2)
>>> B = dict(c=3, d=4)
>>> A.update(B)
>>> A
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> B
{'c': 3, 'd': 4}</pre>



<p>We have just updated A. Thus all the key-value pairs from B have been added to A. B has not changed. </p>



<p>If A and B some keys, B&#8217;s value will replace A&#8217;s. This is because A is updated by B and so takes all of B&#8217;s values (not the other way around).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> A = dict(a=1, b=2)
>>> B = dict(b=100)
>>> A.update(B)
 
# A now contains B's values
>>> A
{'a': 1, 'b': 100}
 
# B is unchanged
>>> B
{'b': 100}</pre>



<p> You can also pass a sequence of tuples or keyword arguments to update(), like you would with the dict() constructor. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> A = dict(a=1, b=2)
# Sequence of tuples
>>> B = [('c', 3), ('d', 4)]
>>> A.update(B)
>>> A
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
 
>>> A = dict(a=1, b=2)
# Pass key-value pairs as keyword arguments
>>> A.update(c=3, d=4)
>>> A
{'a': 1, 'b': 2, 'c': 3, 'd': 4}</pre>



<h3 class="wp-block-heading">dict.pop() &#8211; remove a key and return its value</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> A = dict(a=1, b=2)
>>> A.pop('a')
1
>>> A
{'b': 2}</pre>



<p> If you try call dict.pop() with a key that is not in the dictionary, Python raises a KeyError. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> A.pop('non_existent_key')
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
KeyError: 'non_existent_key'</pre>



<p>Like the get() method, you can specify an optional second argument. This is returned if the key is not in the dictionary and so avoids KeyErrors.  </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> A.pop('non_existent_key', 'not here')
'not here'</pre>



<h3 class="wp-block-heading"> dict.popitem() &#8211; remove a random key-value pair and return it as a tuple </h3>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> A = dict(a=1, b=2, c=3)
# Your results will probably differ
>>> A.popitem()
('c', 3)
>>> A
{'a': 1, 'b': 2}
>>> A.popitem()
('b', 2)
>>> A
{'a': 1}</pre>



<p> If the dictionary is empty, Python raises a KeyError.&nbsp; </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> A = dict()
>>> A.popitem()
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
KeyError: 'popitem(): dictionary is empty'</pre>



<h2 class="wp-block-heading">Python Loop Through Dictionary &#8211; In Detail</h2>



<p>There are several common situations you will encounter when iterating over dictionaries. Python has developed several methods to help you work more efficiently.</p>



<p>But before we head any further, please remember the following:</p>



<p>NEVER EVER use bracket notation when iterating over a dictionary. If there are any errors, the whole iteration will break and you will not be happy.</p>



<p>The standard Python notation for incrementing numbers or <a href="https://blog.finxter.com/python-list-append/" target="_blank" rel="noreferrer noopener" title="Python List append() Method">appending to lists</a> is</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Counting
my_num = 0
for thing in other_thing:
    my_num += 1
 
# Appending to lists
my_list = []
for thing in other_thing:
    my_list.append(thing)</pre>



<p>
This follows the standard pattern:</p>



<ol class="wp-block-list"><li>Initialise &#8217;empty&#8217; object</li><li>Begin for loop</li><li>Add things to that object</li></ol>



<p>When iterating over a dictionary, our values can be numbers or list-like. Thus we can add or we can append to values. It would be great if our code followed the above pattern. But&#8230;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> my_dict = {}
>>> for thing in other_thing:
        my_dict['numerical_key'] += 1
Traceback (most recent call last):
  File "&lt;stdin>", line 2, in &lt;module>
KeyError: 'numerical_key'
 
>>> for thing in other_thing:
        my_dict['list_key'].append(thing)
Traceback (most recent call last):
  File "&lt;stdin>", line 2, in &lt;module>
KeyError: 'list_key'</pre>



<p>Unfortunately, both raise a KeyError. Python tells us the key do not exist and so we cannot increment its value. Thus we must first create a key-value pair before we do anything with it. </p>



<p>We&#8217;ll now show 4 ways to solve this problem:</p>



<ol class="wp-block-list"><li>Manually initialise a key if it does not exist</li><li>The get() method</li><li>The setdefault() method</li><li>The defaultdict()</li></ol>



<p>We&#8217;ll explain this through some examples, so let&#8217;s go to the setup. </p>



<p>Three friends &#8211; Adam, Bella and Cara, have gone out for a meal on Adam&#8217;s birthday. They have stored their starter, main and drinks orders in one list. The price of each item is in another list. We will use this data to construct different dictionaries.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">people = ['Adam', 'Bella', 'Cara',
          'Adam', 'Bella', 'Cara',
          'Adam', 'Bella', 'Cara',]
 
food = ['soup', 'bruschetta', 'calamari',   # starter
        'burger', 'calzone', 'pizza',       # main
        'coca-cola', 'fanta', 'water']      # drink
 
# Cost of each item in £
prices = [3.20, 4.50, 3.89,
          12.50, 15.00, 13.15,
          3.10, 2.95, 1.86]
 
# Zip data together to allow iteration
# We only need info about the person and the price
meal_data = zip(people, prices)
</pre>



<p>Our three friends are very strict with their money. They want to pay exactly the amount they ordered. So we will create a dictionary containing the total cost for each person. This is a numerical incrementation problem. </p>



<h3 class="wp-block-heading">Manually Initialize a Key</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Initialise empty dict
total = {}
 
# Iterate using descriptive object names
for (person, price) in meal_data:
 
    # Create new key and set value to 0 if key doesn't yet exist
    if person not in total:
        total[person] = 0
    
    # Increment the value by the price of each item purchased.
    total[person] += price
 
>>> total
{'Adam': 18.8, 'Bella': 22.45, 'Cara': 18.9}</pre>



<p>We write an if statement which checks if the key is already in the dictionary. If it isn&#8217;t, we set the value to 0. If it is, Python does not execute the if statement. We then increment using the expected syntax. </p>



<p>This works well but requires quite a few lines of code. Surely we can do better?</p>



<h3 class="wp-block-heading">Python Dict get() Method When Iterating</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Reinitialise meal_data as we have already iterated over it
meal_data = zip(people, prices)
 
total = {}
for (person, price) in meal_data:
 
    # get method returns 0 the first time we call it
    # and returns the current value subsequent times
    total[person] = total.get(person, 0) + price
 
>>> total
{'Adam': 18.8, 'Bella': 22.45, 'Cara': 18.9}</pre>



<p>We&#8217;ve got it down to one line!</p>



<p>We pass get() a second value which is returned if the key is not in the dictionary. In this case, we choose 0 like the above example. The first time we call get() it returns 0. We have just initialised a key-value pair! In the same line, we add on &#8216;price&#8217;. The next time we call get(), it returns the current value and we can add on &#8216;price&#8217; again. </p>



<p>This method does not work for appending. You need some extra lines of code. We will look at the setdefault() method instead. </p>



<h3 class="wp-block-heading">Python Dict setdefault() Method</h3>



<p>The syntax of this method makes it an excellent choice for modifying a key&#8217;s value via the <code>append()</code> method. </p>



<p>First we will show why it&#8217;s not a great choice to use if you are incrementing with numbers. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">meal_data = zip(people, prices)
total = {}
for (person, price) in meal_data:
 
    # Set the initial value of person to 0
    total.setdefault(person, 0)
 
    # Increment by price
    total[person] += price
 
0
0
0
3.2
4.5
3.89
15.7
19.5
17.04
>>> total
{'Adam': 18.8, 'Bella': 22.45, 'Cara': 18.9}</pre>



<p>It works but requires more lines of code than get() and prints lots of numbers to the screen. Why is this?</p>



<p>The setdefault() method takes two arguments:</p>



<ol class="wp-block-list"><li>The key you wish to set a default value for</li><li>What you want the default value to be</li></ol>



<p>So setdefault(person, 0) sets the default value of person to be 0. </p>



<p>It always returns one of two things:</p>



<ol class="wp-block-list"><li>The current value of the key</li><li>If the key does not exist, it returns the default value provided</li></ol>



<p>This is why the numbers are printed to the screen. They are the values of &#8216;person&#8217; at each iteration. </p>



<p>Clearly this is not the most convenient method for our current problem. If we do 100k iterations, we don&#8217;t want 100k numbers printed to the screen. </p>



<p>So we recommend using the get() method for numerical calculations. </p>



<p>Let&#8217;s see it in action with lists and sets. In this dictionary, each person&#8217;s name is a key. Each value is a list containing the price of each item they ordered (starter, main, dessert).&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">meal_data = zip(people, prices)
individual_bill = {}
 
for (person, price) in meal_data:
 
    # Set default to empty list and append in one line!
    individual_bill.setdefault(person, []).append(price)
 
>>> individual_bill
{'Adam': [3.2, 12.5, 3.1], 
'Bella': [4.5, 15.0, 2.95], 
'Cara': [3.89, 13.15, 1.86]}</pre>



<p>Now we see the true power of setdefault()! Like the get method in our numerical example, we initialise a default value and modify it in one line!</p>



<p>Note: setdefault() calculates the default value every time it is called. This may be an issue if your default value is expensive to compute. Get() only calculates the default value if the key does not exist. Thus get() is a better choice if your default value is expensive. Since most default values are &#8216;zeros&#8217; such as 0, [ ] and { }, this is not an issue for most cases. </p>



<p>We&#8217;ve seen three solutions to the problem now. We&#8217;ve got the code down to 1 line. But the syntax for each has been different to what we want. Now let&#8217;s see something that solves the problem exactly as we&#8217;d expect: introducing defaultdict!</p>



<h3 class="wp-block-heading">Python defaultdict()</h3>



<p>Let&#8217;s solve our numerical incrementation problem:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Import from collections module
from collections import defaultdict
 
meal_data = zip(people, prices)
 
# Initialise with int to do numerical incrementation
total = defaultdict(int)
 
# Increment exactly as we want to!
for (person, price) in meal_data:
    total[person] += price
 
>>> total
defaultdict(&lt;class 'int'>, {'Adam': 18.8, 'Bella': 22.45, 'Cara': 18.9})</pre>



<p>Success!! But what about our list problem? </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from collections import defaultdict
 
meal_data = zip(people, prices)
 
# Initialise with list to let us append
individual_bill = defaultdict(list)
 
for (person, price) in meal_data:
    individual_bill[person].append(price)
 
>>> individual_bill
defaultdict(&lt;class 'list'>, {'Adam': [3.2, 12.5, 3.1], 
                             'Bella': [4.5, 15.0, 2.95], 
                             'Cara': [3.89, 13.15, 1.86]})</pre>



<p>The defaultdict is part of the built-in collections module. So before we use it, we must first import it. </p>



<p>Defaultdict is the same as a normal Python dictionary except:</p>



<ol class="wp-block-list"><li>It takes a callable data type as an argument</li><li>When it meets a key for the first time, the default value is set as the &#8216;zero&#8217; for that data type. For int it is 0, for list it&#8217;s an empty list [ ] etc..</li></ol>



<p>Thus you will never get a KeyError! Plus and initialising default values is taken care of automatically!</p>



<p>We have now solved the problem using the same syntax for lists and numbers! </p>



<p>Now let&#8217;s go over some special cases for defaultdict.</p>



<h3 class="wp-block-heading">Python defaultdict() Special Cases</h3>



<p>Above we said it&#8217;s not possible to get a KeyError when using defaultdict. This is only true if you correctly initialise your dict. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Initialise without an argument
>>> bad_dict = defaultdict()
>>> bad_dict['key']
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
KeyError: 'key'
 
# Initialise with None
>>> another_bad_dict = defaultdict(None)
>>> another_bad_dict['another_key']
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
KeyError: 'another_key'</pre>



<p>Let&#8217;s say you initialise defaultdict without any arguments. Then Python raises a KeyError if you call a key not in the dictionary. This is the same as initialising with None and defeats the whole purpose of defaultdict. </p>



<p>The issue is that None is not callable. Yet you can get defaultdict to return None by using a <a href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/">lambda function</a>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> none_dict = defaultdict(lambda: None)
>>> none_dict['key']
>>></pre>



<p>Note that you cannot increment or append to None. Make sure you choose your default value to match the problem you are solving!</p>



<p>Whilst we&#8217;re here, let&#8217;s take a look at some more dictionaries in the collections module. </p>



<h2 class="wp-block-heading">OrderedDict&nbsp;</h2>



<p>Earlier we said that dictionaries preserve their order from Python 3.7 onwards. So why do we need something called OrderedDict?</p>



<p>As the name suggests, OrderedDict preserves the order elements are added. But two OrderedDicts are the same if and only if their elements are in the same order. This is not the case with normal dicts. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> from collections import OrderedDict
 
# Normal dicts preserve order but don't use it for comparison
>>> normal1 = dict(a=1, b=2)
>>> normal2 = dict(b=2, a=1)
>>> normal1 == normal2
True
 
# OrderedDicts preserve order and use it for comparison
>>> ordered1 = OrderedDict(a=1, b=2)
>>> ordered2 = OrderedDict(b=2, a=1)
>>> ordered1 == ordered2
False</pre>



<p>Other than that, OrderedDict has all the same properties as a regular dictionary. If your elements must be in a particular order, then use OrderedDict!</p>



<h2 class="wp-block-heading">Counter()</h2>



<p>Let&#8217;s say we want to count how many times each word appears in a piece of text (a common thing to do in NLP). We&#8217;ll use <strong><em>The Zen of Python</em></strong> for our example. If you don&#8217;t know what it is, run </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import this</pre>



<p>I&#8217;ve stored it in the list zen_words where each element is a single word.</p>



<p>We can manually count each word using defaultdict. But printing it out with the most frequent words occurring first is a bit tricky. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> from collections import defaultdict
>>> word_count = defaultdict(int)
>>> for word in zen_words:
        word_count[word] += 1
 
# Define function to return the second value of a tuple
>>> def select_second(tup):
        return tup[1]
 
# Reverse=True - we want the most common first
# word_count.items() - we want keys and values
# sorted() returns a list, so wrap in dict() to return a dict
 
>>> dict(sorted(word_count.items(), reverse=True, key=select_second))
{'is': 10, 
'better': 8, 
'than': 8, 
'to': 5, 
...}</pre>



<p>As counting is quite a common process, the Counter() dict subclass was created. It is complex enough that we could write a whole article about it.&nbsp;</p>



<p>For brevity, we will include the most basic use cases and let the reader peruse<a href="https://docs.python.org/3.8/library/collections.html#collections.Counter"> the docs</a> themselves. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> from collections import Counter
>>> word_count = Counter(zen_words)
>>> word_count
Counter({'is': 10, 'better': 8, 'than': 8, 'to': 5, ...})</pre>



<p> You can pass any iterable or dictionary to Counter(). It returns a dictionary in descending order of counts </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> letters = Counter(['a', 'b', 'c', 'c', 'c', 'c', 'd', 'd', 'a'])
>>> letters
Counter({'c': 4, 'a': 2, 'd': 2, 'b': 1})
 
# Count of a missing key is 0
>>> letters['z']
0</pre>



<h2 class="wp-block-heading">Reversed()</h2>



<p>In Python 3.8 they introduced the <code>reversed()</code> function for dictionaries! It returns an iterator. It iterates over the dictionary in the opposite order to how the key-value pairs were added. If the key-value pairs have no order, reversed() will not give them any further ordering. If you want to sort the keys alphabetically for example, use <code><a href="https://blog.finxter.com/python-list-sort/" title="Python List sort() – The Ultimate Guide">sorted()</a></code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Python 3.8
 
# Reverses the order key-value pairs were added to the dict
>>> ordered_dict = dict(a=1, b=2, c=3)
>>> for key, value in reversed(ordered_dict.items()):
        print(key, value)
c 3
b 2
a 1
 
# Does not insert order where there is none.
>>> unordered_dict = dict(c=3, a=1, b=2)
>>> for key, value in reversed(unordered_dict.items()):
        print(key, value)
b 2
a 1
c 3
 
# Order unordered_dict alphabetically using sorted()
>>> dict(sorted(unordered_dict.items()))
{'a': 1, 'b': 2, 'c': 3}</pre>



<p>Since it&#8217;s an iterator, remember to use the keys(), values() and items() methods to select the elements you want. If you don&#8217;t specify anything, you&#8217;ll iterate over the keys.</p>



<h2 class="wp-block-heading">Dictionary Comprehensions</h2>



<p>A wonderful feature of dictionaries, and Python in general, is the comprehension. This lets you create dictionaries in a clean, easy to understand and Pythonic manner. You must use curly braces {} to do so (not dict()).</p>



<p>We&#8217;ve already seen that if you have two lists, you can create a dictionary from them using dict(zip()).&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">names = ['Adam', 'Beth', 'Charlie', 'Dani', 'Ethan']
countries = ['Argentina', 'Bulgaria', 'Colombia', 'Denmark', 'Estonia']
 
dict_zip = dict(zip(names, countries))
 
>>> dict_zip
{'Adam': 'Argentina',
'Beth': 'Bulgaria',
'Charlie': 'Colombia',
'Dani': 'Denmark',
'Ethan': 'Estonia'}</pre>



<p> We can also do this using a for loop </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> new_dict = {}
>>> for name, country in zip(names, countries):
        new_dict[name] = country
 
>>> new_dict
{'Adam': 'Argentina',
'Beth': 'Bulgaria',
'Charlie': 'Colombia',
'Dani': 'Denmark',
'Ethan': 'Estonia'}</pre>



<p>We initialize our dict and iterator variables with descriptive names. To iterate over both lists at the same time we <a href="https://blog.finxter.com/zip-unzip-python/" target="_blank" rel="noreferrer noopener" title="Zip &amp; Unzip: How Does It Work in Python?">zip </a>them together. Finally, we add key-value pairs as desired. This takes 3 lines. </p>



<p>Using a comprehension turns this into one line. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dict_comp = {name: country for name, country in zip(names, countries)}
 
>>> dict_comp
{'Adam': 'Argentina',
'Beth': 'Bulgaria',
'Charlie': 'Colombia',
'Dani': 'Denmark',
'Ethan': 'Estonia'}</pre>



<p>They are a bit like for loops in reverse. First, we state what we want our key-value pairs to be. Then we use the same for loop as we did above. Finally, we wrap everything in curly braces. </p>



<p>Note that every comprehension can be written as a for loop. If you ever get results you don&#8217;t expect, try it as a for loop to see what is happening. </p>



<p>Here&#8217;s a common mistake</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dict_comp_bad = {name: country 
                 for name in names 
                 for country in countries}
 
>>> dict_comp_bad
{'Adam': 'Estonia',
'Beth': 'Estonia',
'Charlie': 'Estonia',
'Dani': 'Estonia',
'Ethan': 'Estonia'}</pre>



<p> What&#8217;s going on? Let&#8217;s write it as a for loop to see. First, we&#8217;ll write it out to make sure we are getting the same, undesired, result. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">bad_dict = {}
for name in names:
    for country in countries:
        bad_dict[name] = country
 
>>> bad_dict
{'Adam': 'Estonia',
'Beth': 'Estonia',
'Charlie': 'Estonia',
'Dani': 'Estonia',
'Ethan': 'Estonia'}</pre>



<p> Now we&#8217;ll use the bug-finder&#8217;s best friend: the print statement!  </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Don't initialise dict to just check for loop logic
for name in names:
    for country in countries:
        print(name, country)
Adam Argentina
Adam Bulgaria
Adam Colombia
Adam Denmark
Adam Estonia
Beth Argentina
Beth Bulgaria
Beth Colombia
...
Ethan Colombia
Ethan Denmark
Ethan Estonia</pre>



<p>Here we remove the dictionary to check what is actually happening in the loop. Now we see the problem! The issue is we have nested for loops. The loop says: for each name pair it with every country. Since dictionary keys can only appear, the value gets overwritten on each iteration. So each key&#8217;s value is the final one that appears in the loop &#8211; &#8216;Estonia&#8217;.</p>



<p>The solution is to remove the nested for loops and use zip() instead. </p>



<h3 class="wp-block-heading">Python Nested Dictionaries with Dictionary Comprehensions</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">nums = [0, 1, 2, 3, 4, 5]
 
dict_nums = {n: {'even': n % 2 == 0,
                 'square': n**2,
                 'cube': n**3,
                 'square_root': n**0.5}
             for n in nums}
 
# Pretty print for ease of reading
>>> pprint(dict_nums)
{0: {'cube': 0, 'even': True, 'square': 0, 'square_root': 0.0},
1: {'cube': 1, 'even': False, 'square': 1, 'square_root': 1.0},
2: {'cube': 8, 'even': True, 'square': 4, 'square_root': 1.4142135623730951},
3: {'cube': 27, 'even': False, 'square': 9, 'square_root': 1.7320508075688772},
4: {'cube': 64, 'even': True, 'square': 16, 'square_root': 2.0},
5: {'cube': 125, 'even': False, 'square': 25, 'square_root': 2.23606797749979}}</pre>



<p>This is where comprehensions become powerful. We define a dictionary within a dictionary to create lots of information in a few lines of code. The syntax is exactly the same as above but our value is more complex than the first example.</p>



<p>Remember that our key value pairs must be unique and so we cannot create a dictionary like the following</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> nums = [0, 1, 2, 3, 4, 5]
>>> wrong_dict = {'number': num, 'square': num ** 2 for num in nums}
  File "&lt;stdin>", line 1
    wrong_dict = {'number': num, 'square': num ** 2 for num in nums}
                                                    ^
SyntaxError: invalid syntax</pre>



<p>We can only define one pattern for key-value pairs in a comprehension. But if you could define more, it wouldn&#8217;t be very helpful. We would overwrite our key-value pairs on each iteration as keys must be unique. </p>



<h3 class="wp-block-heading">If-Elif-Else Statements </h3>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 
# Just the even numbers
even_squares = {n: n ** 2 for n in nums
                if n % 2 == 0}
 
# Just the odd numbers
odd_squares = {n: n ** 2 for n in nums
               if n % 2 == 1}
 
>>> even_dict
{0: 0, 2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
 
>>> odd_dict
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}</pre>



<p>We can apply if conditions after the for statement. This affects all the values you are iterating over. </p>



<p>You can also apply them to your key and value definitions. We&#8217;ll now create different key-value pairs based on whether a number is odd or even.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Use parenthesis to aid readability
different_vals = {n: ('even' if n % 2 == 0 else 'odd')
                  for n in range(5)}
 
>>> different_vals
{0: 'even', 1: 'odd', 2: 'even', 3: 'odd', 4: 'even'}</pre>



<p> We can get really complex and use if/else statements in both the key-value definitions and after the for loop! </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Change each key using an f-string
{(f'{n}_cubed' if n % 2 == 1 else f'{n}_squared'): 
 
# Cube odd numbers, square even numbers
 (n ** 3 if n % 2 == 1 else n ** 2)
 
# The numbers 0-10 inclusive
 for n in range(11)
 
# If they are not multiples of 3
 if n % 3 != 0}
 
{'1_cubed': 1, '2_squared': 4, '4_squared': 16, '5_cubed': 125, '7_cubed': 343, '8_squared': 64, '10_squared': 100}</pre>



<p>It is relatively simple to do this using comprehensions. Trying to do so with a for loop or dict() constructor would be much harder. </p>



<h2 class="wp-block-heading">Merging Two Dictionaries</h2>



<p>Let&#8217;s say we have two dictionaries A and B. We want to create a dictionary, C, that contains all the key-value pairs of A and B. How do we do this? </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> A = dict(a=1, b=2)
>>> B = dict(c=3, d=4)
 
# Update method does not create a new dictionary
>>> C = A.update(B)
>>> C
>>> type(C)
&lt;class 'NoneType'>
 
>>> A
{'a': 1, 'b': 2, 'c': 3, 'd': 4}</pre>



<p>Using merge doesn&#8217;t work. It modifies A in place and so doesn&#8217;t return anything. </p>



<p>Before Python 3.5, you had to write a function to do this. In Python 3.5 they introduced this wonderful bit of syntax.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Python >= 3.5
>>> A = dict(a=1, b=2)
>>> B = dict(c=3, d=4)
>>> C = {**A, **B}
>>> C
{'a': 1, 'b': 2, 'c': 3, 'd': 4}</pre>



<p>We use ** before each dictionary to &#8216;unpack&#8217; all the key-value pairs. </p>



<p>The syntax is very simple: a comma-separated list of dictionaries wrapped in curly braces. You can do this for an arbitrary number of dictionaries. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">A = dict(a=1, b=2)
B = dict(c=3, d=4)
C = dict(e=5, f=6)
D = dict(g=7, h=8)
>>> all_the_dicts = {**A, **B, **C, **D}
>>> all_the_dicts
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8}</pre>



<p>Finally, what happens if the dicts share key-value pairs? </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> A = dict(a=1, b=2)
>>> B = dict(a=999)
>>> B_second = {**A, **B}
>>> A_second = {**B, **A}
 
# Value of 'a' taken from B
>>> B_second
{'a': 999, 'b': 2}
 
# Value of 'a' taken from A
>>> A_second
{'a': 1, 'b': 2}</pre>



<p>As is always the case with Python dictionaries, a key&#8217;s value is dictated by its last assignment. The dict B_second first takes A&#8217;s values then take&#8217;s B&#8217;s. Thus any shared keys between A and B will be overwritten with B&#8217;s values. The opposite is true for A_second.</p>



<p>Note: if a key&#8217;s value is overridden, the position of that key in the dict does not change.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> D = dict(g=7, h=8)
>>> A = dict(a=1, g=999)
>>> {**D, **A}
 
# 'g' is still in the first position despite being overridden with A's value
{'g': 999, 'h': 8, 'a': 1}</pre>



<h2 class="wp-block-heading">Conclusion</h2>



<p>You now know almost everything you’ll ever need to know to use Python Dictionaries. Well done! Please bookmark this page and refer to it as often as you need!</p>



<p>If you have any questions post them in the comments and we&#8217;ll get back to you as quickly as possible.</p>



<p><strong>If you love Python and want to become a freelancer, there is <a href="https://www.digistore24.com/redir/261950/adsmurphy/">no better course out there than this one</a>:</strong></p>



<figure class="wp-block-image size-medium"><a href="https://www.digistore24.com/redir/261950/adsmurphy/"><img loading="lazy" decoding="async" width="300" height="239" src="https://blog.finxter.com/wp-content/uploads/2019/04/smartmockups_jucpzuxy-1-300x239.png" alt="" class="wp-image-2740" srcset="https://blog.finxter.com/wp-content/uploads/2019/04/smartmockups_jucpzuxy-1-300x239.png 300w, https://blog.finxter.com/wp-content/uploads/2019/04/smartmockups_jucpzuxy-1-768x611.png 768w, https://blog.finxter.com/wp-content/uploads/2019/04/smartmockups_jucpzuxy-1-100x80.png 100w, https://blog.finxter.com/wp-content/uploads/2019/04/smartmockups_jucpzuxy-1-670x533.png 670w, https://blog.finxter.com/wp-content/uploads/2019/04/smartmockups_jucpzuxy-1.png 786w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a></figure>



<p>I bought it myself and it is why you are reading these words today.&nbsp;</p>



<h2 class="wp-block-heading">About the Author</h2>



<p>This article is contributed by Finxter user <strong>Adam Murphy</strong> (data scientist, <a href="https://finxter.com/">grandmaster of Python code</a>):</p>



<p><em>I am a self-taught programmer with a First Class degree in 
Mathematics from Durham University and have been coding since June 2019.</em></p>



<p><em>I am well versed in the fundamentals of web scraping and data science and can get you a wide variety of information from the web very quickly.</em></p>



<p><em>I recently scraped information about all watches that Breitling and Rolex sell in just 48 hours and am confident I can deliver datasets of similar quality to you whatever your needs.  </em></p>



<p><em>Being a native English speaker, my communication skills are excellent and I am available to answer any questions you have and will provide regular updates on the progress of my work.</em></p>



<p>If you want to hire Adam, check out his <a href="https://www.upwork.com/o/profiles/users/_~01153ca9fd0099730e/">Upwork profile</a>!</p>



<h2 class="wp-block-heading">References</h2>



<ol class="wp-block-list"><li><a href="https://www.dictionary.com/">https://www.dictionary.com/</a></li><li><a href="https://tinyurl.com/yg6kgy9h">https://tinyurl.com/yg6kgy9h</a></li><li><a href="https://stackoverflow.com/questions/7886355/defaultdictnone">https://stackoverflow.com/questions/7886355/defaultdictnone</a></li><li><a href="https://www.datacamp.com/community/tutorials/python-dictionary-tutorial">https://www.datacamp.com/community/tutorials/python-dictionary-tutorial</a></li><li><a href="https://docs.python.org/3.8/tutorial/datastructures.html#dictionaries">https://docs.python.org/3.8/tutorial/datastructures.html#dictionaries</a></li><li><a href="https://stackoverflow.com/questions/526125/why-is-python-ordering-my-dictionary-like-so">https://stackoverflow.com/questions/526125/why-is-python-ordering-my-dictionary-like-so</a></li><li><a href="https://stackoverflow.com/a/378987/11829398">https://stackoverflow.com/a/378987/11829398</a></li><li><a href="https://en.wikipedia.org/wiki/Hash_function">https://en.wikipedia.org/wiki/Hash_function</a></li><li><a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict">https://docs.python.org/2/library/collections.html#collections.OrderedDict</a></li><li><a href="https://www.quora.com/What-are-hashable-types-in-Python">https://www.quora.com/What-are-hashable-types-in-Python</a></li><li><a href="https://hg.python.org/cpython/file/default/Objects/dictobject.c">https://hg.python.org/cpython/file/default/Objects/dictobject.c</a></li><li><a href="https://www.dictionary.com/browse/facetious?s=t">https://www.dictionary.com/browse/facetious?s=t</a></li><li><a href="https://thispointer.com/python-how-to-copy-a-dictionary-shallow-copy-vs-deep-copy/">https://thispointer.com/python-how-to-copy-a-dictionary-shallow-copy-vs-deep-copy/</a></li><li><a href="https://docs.python.org/3.8/library/collections.html#collections.Counter">https://docs.python.org/3.8/library/collections.html#collections.Counter</a></li><li><a href="https://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file">https://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file</a></li><li><a href="https://realpython.com/python-dicts/#built-in-dictionary-methods">https://realpython.com/python-dicts/#built-in-dictionary-methods</a></li><li><a href="https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression">https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression</a></li></ol>



<h2 class="wp-block-heading">Where to Go From Here?</h2>



<p>Congratulations! You&#8217;ve successfully mastered dictionaries in Python! Now, let&#8217;s dive into Python sets.</p>



<figure class="wp-block-embed-wordpress wp-block-embed is-type-wp-embed is-provider-finxter"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="sksjDKxUhM"><a href="https://blog.finxter.com/sets-in-python/">The Ultimate Guide to Python Sets – with Harry Potter Examples</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;The Ultimate Guide to Python Sets – with Harry Potter Examples&#8221; &#8212; Be on the Right Side of Change" src="https://blog.finxter.com/sets-in-python/embed/#?secret=DoFQDgCYgR#?secret=sksjDKxUhM" data-secret="sksjDKxUhM" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p></p>



<p></p>



<p></p>
<p>The post <a href="https://blog.finxter.com/python-dictionary/">Python Dictionary &#8211; The Ultimate Guide</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python Functions and Tricks Cheat Sheet</title>
		<link>https://blog.finxter.com/python-cheat-sheet-functions-and-tricks/</link>
					<comments>https://blog.finxter.com/python-cheat-sheet-functions-and-tricks/#respond</comments>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Mon, 22 Jun 2020 10:21:00 +0000</pubDate>
				<category><![CDATA[Cheat Sheets]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Productivity]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python One-Liners]]></category>
		<category><![CDATA[cheat sheet]]></category>
		<category><![CDATA[Python 3]]></category>
		<category><![CDATA[python cheat sheet]]></category>
		<category><![CDATA[Python functions]]></category>
		<category><![CDATA[Python hacks]]></category>
		<category><![CDATA[Python tricks]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=449</guid>

					<description><![CDATA[<p>Python cheat sheets are the 80/20 principle applied to coding: learn 80% of the language features in 20% of the time.Download and pin this cheat sheet to your wall until you feel confident using all these tricks. Download PDF for Printing Try It Yourself: Exercise: Modify each function and play with the output! Here&#8217;s the ... <a title="Python Functions and Tricks Cheat Sheet" class="read-more" href="https://blog.finxter.com/python-cheat-sheet-functions-and-tricks/" aria-label="Read more about Python Functions and Tricks Cheat Sheet">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-cheat-sheet-functions-and-tricks/">Python Functions and Tricks Cheat Sheet</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Python cheat sheets are the 80/20 principle applied to coding: learn 80% of the language features in 20% of the time.<br>Download and pin this cheat sheet to your wall until you feel confident using all these tricks. <br><a href="https://blog.finxter.com/wp-content/uploads/2018/07/CheatSheet-Python-5-Functions-and-Tricks.pdf" target="_blank" rel="noreferrer noopener" title="https://blog.finxter.com/wp-content/uploads/2018/07/CheatSheet-Python-5-Functions-and-Tricks.pdf"><img decoding="async" src="https://blog.finxter.com/wp-content/uploads/2018/07/CheatSheet-Python-5-Functions-and-Tricks-791x1024.png" alt="CheatSheet Python 5 - Functions and Tricks" style="width: undefinedpx;"></a><br><a href="https://blog.finxter.com/wp-content/uploads/2018/07/CheatSheet-Python-5-Functions-and-Tricks.pdf" target="_blank" rel="noreferrer noopener"><br>Download PDF for Printing</a></p>






<p><strong>Try It Yourself:</strong></p>



<iframe loading="lazy" src="https://trinket.io/embed/python/dab44ebcf3" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="800" frameborder="0"></iframe>



<p><em><strong>Exercise</strong>: Modify each function and play with the output!</em></p>



<p>Here&#8217;s the code for copy&amp;paste:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 1. map(func, iter)
m = map(lambda x: x[0], ['red', 'green', 'blue'])
print(list(m))
# ['r', 'g', 'b']


# 2. map(func, i1, ...,ik)
l1 = [0, 2, 2]
l2 = ['apple', 'orange', 'banana']
m = map(lambda x, y: str(x) + ' ' + str(y) + 's', l1, l2)
print(list(m))
# ['0 apples', '2 oranges', '2 bananas']


# 3. string.join(iter)
print(' marries '.join(['Alice', 'Bob']))
# Alice marries Bob


# 4. filter(func, iterable)
print(list(filter(lambda x: x>17, [1, 15, 17, 18])))
# [18]


# 5. string.strip()
print("    \n   \t  42  \t ".strip())
# 42


# 6. sorted(iter)
print(sorted([8, 3, 2, 42, 5]))
# [2, 3, 5, 8, 42]


# 7. sorted(iter, key=key)
print(sorted([8, 3, 2, 42, 5], key=lambda x: 0 if x==42 else x))
# [42, 2, 3, 5, 8]


# 8. help(func)
help(str.upper)
'''
Help on method_descriptor:

upper(self, /)
    Return a copy of the string converted to uppercase.
'''


# 9. zip(i1, i2, ...)
print(list(zip(['Alice', 'Anna'], ['Bob', 'Jon', 'Frank'])))
# [('Alice', 'Bob'), ('Anna', 'Jon')]


# 10. Unzip
print(list(zip(*[('Alice', 'Bob'), ('Anna', 'Jon')])))
# [('Alice', 'Anna'), ('Bob', 'Jon')]


# 11. Enumerate
print(list(enumerate(['Alice', 'Bob', 'Jon'])))
# [(0, 'Alice'), (1, 'Bob'), (2, 'Jon')]
</pre>



<p>The following tutorials address those functions in great detail (including videos on the most important functions).</p>



<p><strong>Related Articles:</strong></p>



<ul class="wp-block-list"><li><a href="https://blog.finxter.com/daily-python-puzzle-string-encrpytion-ord-function-map-function/" title="Mastering the Python Map Function [+Video]" target="_blank" rel="noreferrer noopener">Map Function</a></li><li><a href="https://blog.finxter.com/python-join-list/" title="Python Join List [Ultimate Guide]" target="_blank" rel="noreferrer noopener">String Join</a></li><li><a href="https://blog.finxter.com/how-to-filter-a-list-in-python/" title="How to Filter a List in Python?" target="_blank" rel="noreferrer noopener">Filtering Lists</a></li><li><a href="https://blog.finxter.com/python-trim-string/" title="Python Trim String [Ultimate Guide]" target="_blank" rel="noreferrer noopener">Strip and Trim</a> </li><li><a href="https://blog.finxter.com/python-list-sort/" title="Python List sort() – The Ultimate Guide" target="_blank" rel="noreferrer noopener">Python Sorting</a></li><li><a href="https://blog.finxter.com/zip-unzip-python/" title="Zip &amp; Unzip: How Does It Work in Python?" target="_blank" rel="noreferrer noopener">Zip and Unzip</a></li></ul>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Zip &amp; Unzip: How Does It Work in Python?" width="937" height="527" src="https://www.youtube.com/embed/7zx603xCri4?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Know someone who would benefit from this cheat sheet? Share it with your friends!</p>



<p><a href="https://blog.finxter.com/subscribe/" target="_blank" rel="noreferrer noopener" title="Subscribe">Simplify learning Python and register for the free 5x Python cheat sheet course.</a></p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow">
<p><strong>Related Articles:</strong></p>



<ul class="wp-block-list"><li><a href="https://blog.finxter.com/collection-5-cheat-sheets-every-python-coder-must-own/" target="_blank" rel="noreferrer noopener" title="[Collection] 11 Python Cheat Sheets Every Python Coder Must Own">[Collection] 11 Python Cheat Sheets Every Python Coder Must Own</a></li><li><a href="https://blog.finxter.com/object-oriented-programming-terminology-cheat-sheet/" target="_blank" rel="noreferrer noopener" title="https://blog.finxter.com/object-oriented-programming-terminology-cheat-sheet/">[Python OOP Cheat Sheet] A Simple Overview of Object-Oriented Programming</a></li><li><a href="https://blog.finxter.com/machine-learning-cheat-sheets/" title="[Collection] 15 Mind-Blowing Machine Learning Cheat Sheets to Pin to Your Toilet Wall" target="_blank" rel="noreferrer noopener">[Collection] 15 Mind-Blowing Machine Learning Cheat Sheets to Pin to Your Toilet Wall</a></li><li><a href="https://blog.finxter.com/python-cheat-sheets/" title="https://blog.finxter.com/python-cheat-sheets/" target="_blank" rel="noreferrer noopener">Your 8+ Free Python Cheat Sheet [Course]</a></li><li><a href="https://blog.finxter.com/python-cheat-sheet/" target="_blank" rel="noreferrer noopener" title="Python Beginner Cheat Sheet: 19 Keywords Every Coder Must Know">Python Beginner Cheat Sheet: 19 Keywords Every Coder Must Know</a></li><li><a href="https://blog.finxter.com/python-cheat-sheet-functions-and-tricks/" title="Python Functions and Tricks Cheat Sheet" target="_blank" rel="noreferrer noopener">Python Functions and Tricks Cheat Sheet</a></li><li><a href="https://blog.finxter.com/python-interview-questions/" target="_blank" rel="noreferrer noopener" title="https://blog.finxter.com/python-interview-questions/">Python Cheat Sheet: 14 Interview Questions</a></li><li><a href="https://blog.finxter.com/pandas-cheat-sheets/" title="[PDF Collection] 7 Beautiful Pandas Cheat Sheets — Post Them to Your Wall" target="_blank" rel="noreferrer noopener">Beautiful Pandas Cheat Sheets</a></li><li><a href="https://blog.finxter.com/collection-10-best-numpy-cheat-sheets-every-python-coder-must-own/" title="[Collection] 10 Best NumPy Cheat Sheets Every Python Coder Must Own" target="_blank" rel="noreferrer noopener">10 Best NumPy Cheat Sheets</a></li><li><a href="https://blog.finxter.com/python-list-methods-cheat-sheet-instant-pdf-download/" title="Python List Methods Cheat Sheet [Instant PDF Download]" target="_blank" rel="noreferrer noopener">Python List Methods Cheat Sheet [Instant PDF Download]</a></li><li><a href="https://blog.finxter.com/cheat-sheet-6-pillar-machine-learning-algorithms/" target="_blank" rel="noreferrer noopener" title="[Cheat Sheet] 6 Pillar Machine Learning Algorithms">[Cheat Sheet] 6 Pillar Machine Learning Algorithms</a></li></ul>
</div></div>
<p>The post <a href="https://blog.finxter.com/python-cheat-sheet-functions-and-tricks/">Python Functions and Tricks Cheat Sheet</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.finxter.com/python-cheat-sheet-functions-and-tricks/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Introduction to Slicing in Python</title>
		<link>https://blog.finxter.com/introduction-to-slicing-in-python/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 13 Jun 2020 18:23:00 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[List Slicing]]></category>
		<category><![CDATA[Python 3]]></category>
		<category><![CDATA[Python Slicing]]></category>
		<category><![CDATA[Slice Function]]></category>
		<category><![CDATA[Slice()]]></category>
		<category><![CDATA[String Slicing]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=731</guid>

					<description><![CDATA[<p>Slicing is a concept to carve out a substring from a given string. Use slicing notation s[start:stop:step] to access every step-th element starting from index start (included) and ending in index stop (excluded). All three arguments are optional, so you can skip them to use the default values (start=0, stop=len(lst), step=1). For example, the expression ... <a title="Introduction to Slicing in Python" class="read-more" href="https://blog.finxter.com/introduction-to-slicing-in-python/" aria-label="Read more about Introduction to Slicing in Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/introduction-to-slicing-in-python/">Introduction to Slicing in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="has-luminous-vivid-amber-background-color has-background"><strong>Slicing is a concept to carve out a substring from a given string. Use slicing notation <code>s[start:stop:step]</code> to access every <code>step</code>-th element starting from index <code>start</code> (included) and ending in index <code>stop</code> (excluded). All three arguments are optional, so you can skip them to use the default values (<code>start=0</code>, <code>stop=len(lst)</code>, <code>step=1</code>). For example, the expression <code>s[2:4]</code> from string <code>'hello'</code> carves out the slice <code>'ll'</code> and the expression <code>s[:3:2]</code> carves out the slice <code>'hl'</code>. </strong></p>



<p>Slicing is a Python-specific concept for carving out a range of values from sequence types such as lists or strings. </p>



<p><strong>Try It Yourself:</strong></p>



<iframe loading="lazy" src="https://repl.it/@finxter/slicingblog?lite=true" scrolling="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals" width="100%" height="600px" frameborder="no"></iframe>



<p>Slicing is one of the most popular Python features. To master Python, you must master slicing first. Any non-trivial Python code base relies on slicing. In other words, the time you invest now in mastering slicing will be repaid a hundredfold during your career. </p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Download</strong>: <a href="https://blog.finxter.com/free-book-coffee-break-python-slicing/" data-type="URL" data-id="https://blog.finxter.com/free-book-coffee-break-python-slicing/" target="_blank" rel="noreferrer noopener">Free Coffee Break Python Slicing eBook</a></p>



<p>Here&#8217;s a 10-min video version of this article&#8211;that shows you everything you need to know about slicing:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="The Ultimate Guide to Slicing in Python" width="937" height="527" src="https://www.youtube.com/embed/D2ZueuWXST8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">[Intermezzo] Indexing Basics</h2>



<p>To bring everybody on the same page, let me quickly explain indices in Python by example. Suppose we have a string <code>'universe'</code>. The indices are simply the positions of the characters of this string. </p>



<figure class="wp-block-table"><table><tbody><tr><td><strong>Index</strong></td><td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td></tr><tr><td><strong>Character</strong></td><td>u</td><td>n</td><td>i</td><td>v</td><td>e</td><td>r</td><td>s</td><td>e</td></tr></tbody></table></figure>



<p>The first character has index <code>0</code>, the second character has index <code>1</code>, and the <code>i</code>-th character has index <code>i-1</code>.</p>



<h2 class="wp-block-heading"> Quick Introduction Slicing</h2>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Info</strong>: The idea of slicing is simple. You carve out a subsequence from a sequence by defining the start and end indices.  But while indexing retrieves only a single character, slicing retrieves a whole substring within an index range. </p>



<p>Use the bracket notation for slicing with the start and end position identifiers. For example, <code>word[i:j]</code> returns the substring starting from index <code>i</code> (included) and ending in index <code>j</code> (excluded).  Forgetting that the end index is excluded is a common source of bugs. <br></p>



<p>You can also skip the position identifier before or after the slicing colon. This indicates that the slice starts from the first or last position, respectively. For example, <code>word[:i] + word[i:]</code> returns the same string as <code>word</code>.</p>



<p><strong>Python puzzle 1: What is the output of this code snippet?</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = 'universe'
print(x[2:4])</pre>



<h2 class="wp-block-heading">The Step Size in Slicing</h2>



<p>For the sake of completeness, let me quickly explain the advanced slicing notation <code>[start:end:step]</code>. The only difference to the previous notation is that it allows you to specify the step size as well. </p>



<p>For example, the command <code>'python'[:5:2]</code> returns every second character up to the fourth character, i.e., the string <code>'pto'</code>.</p>



<p><strong>Python puzzle 2: What is the output of this code snippet?</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = 'universe'
print(x[2::2])</pre>



<h2 class="wp-block-heading">Overshooting Indices in Slicing</h2>



<p class="has-global-color-8-background-color has-background">Slicing is robust even if the end index <em>shoots</em> over the maximal sequence index. You only need to know that nothing unexpected happens if slicing overshoots sequence indices: it just slices to the maximum slice element.</p>



<p>Here is an example.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">word = "galaxy" 
print(word[4:50]) </pre>



<hr class="wp-block-separator has-css-opacity"/>



<h2 class="wp-block-heading">Summary Python Slicing</h2>



<p>Short recap, the slice notation s[start:end:step] carves out a substring from s. The substring consists of all characters between the two characters at the start index (inclusive) and the end index (exclusive). An optional step size indicates how many characters are left out from the original sequence. Here is an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">s = 'sunshine'
print(s[1:5:2])
#'us'
print(s[1:5:1])
#'unsh'</pre>



<hr class="wp-block-separator has-css-opacity"/>



<h2 class="wp-block-heading">Learn Slicing By Doing</h2>



<p>Ok, so let&#8217;s train slicing a little bit. Solve the following puzzle in your head (and check the solution below).</p>



<p><strong>Python Puzzle 3: What is the output of this code snippet?</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># (Shakespeare)
s = "All that glitters is not gold"
print(s[9:-9])
print(s[::10])
print(s[:-4:-1])</pre>



<hr class="wp-block-separator has-css-opacity"/>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>



<p>Let&#8217;s go a bit deeper into slicing to ensure you are getting it 100%.</p>



<p>I have searched the web to find all the little problems new Python coders face with slicing. I will answer six common questions next.</p>



<h3 class="wp-block-heading">1) How to skip slicing indices (e.g., s[::2])?</h3>



<p>The Python interpreter assumes certain default values for <code>s[start:stop:step]</code>. They are: <code>start=0</code>, <code>stop=len(s)</code>, and <code>step=1</code> (in the slice notation: <code>s[::]==s[0:len(s):1]</code>).</p>



<h3 class="wp-block-heading">2) When to use the single colon notation (e.g., s[:]) and when double colon notation (e.g., s[::2])?</h3>



<p>A single colon (e.g. <code>s[1:2]</code>) allows for two arguments, the start and the end index. A double colon (e.g. <code>s[1:2:2]</code>) allows for three arguments, the start index, the end index, and the step size. If the step size is set to the default value 1, we can use the single colon notation for brevity.</p>



<h3 class="wp-block-heading">3) What does a negative step size mean (e.g., s[5:1:-1])?</h3>



<p>This is an interesting feature in Python. A negative step size indicates that we are not slicing from left to right but from right to left. Hence, the start index should be larger or equal to the end index (otherwise, the resulting sequence is empty).</p>



<h3 class="wp-block-heading">4) What are the default indices when using a negative step size (e.g., s[::-1])?</h3>



<p>In this case, the default indices are not <code>start=0</code> and <code>end=len(s)</code> but the other way round: <code>start=len(s)-1</code> and <code>end=-1</code>. Note that the start index is still included, and the end index is still excluded from the slice. Because of that, the default end index is -1 and not 0.</p>



<h3 class="wp-block-heading">5) We have seen many examples of string slicing. How does list slicing work?</h3>



<p>Slicing works the same for all sequence types. For lists, consider the following example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">l = [1, 2, 3, 4]
print(l[2:])
# [3, 4]</pre>



<p>Slicing tuples works in a similar way.</p>



<h3 class="wp-block-heading">6) Why is the last index excluded from the slice?</h3>



<p>The last index is excluded because of two reasons. The first reason is language consistency, e.g., the range function also does not include the end index. The second reason is clarity. Here&#8217;s an example of why it makes sense to exclude the end index from the slice.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">customer_name = 'Hubert'
k = 3 # maximal size of database entry
x = 1 # offset
db_name = customer_name[x:x+k]</pre>



<p>Now suppose the end index would be included. In this case, the total length of the db_name substring would be k + 1 characters. This would be very counter-intuitive.</p>



<hr class="wp-block-separator has-css-opacity"/>



<h2 class="wp-block-heading">Puzzle Solutions</h2>



<p>Here are the solutions to the puzzles in this article.</p>



<p><strong>Puzzle 1:</strong></p>



<pre class="wp-block-preformatted"><code>iv</code></pre>



<p><strong>Puzzle 2</strong>:</p>



<pre class="wp-block-preformatted"><code> ies </code></pre>



<p><strong>Puzzle 3:</strong></p>



<pre class="wp-block-preformatted"><code>glitters is
 Al 
 dlo</code></pre>



<hr class="wp-block-separator has-css-opacity"/>



<h2 class="wp-block-heading">Subscribe to *FREE* Python Training Newsletter </h2>



<p>And become a Python master on auto-pilot:</p>






<p>You can also download our free slicing ebook here:</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Download</strong>: <a href="https://blog.finxter.com/free-book-coffee-break-python-slicing/" data-type="URL" data-id="https://blog.finxter.com/free-book-coffee-break-python-slicing/" target="_blank" rel="noreferrer noopener">Free Coffee Break Python Slicing eBook</a></p>
<p>The post <a href="https://blog.finxter.com/introduction-to-slicing-in-python/">Introduction to Slicing in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>10 Reasons Why Solving Code Puzzles Makes You Smarter</title>
		<link>https://blog.finxter.com/10-reasons-why-solving-code-puzzles-makes-you-smarter/</link>
					<comments>https://blog.finxter.com/10-reasons-why-solving-code-puzzles-makes-you-smarter/#comments</comments>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sun, 16 Feb 2020 10:28:00 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[code puzzle]]></category>
		<category><![CDATA[computer science]]></category>
		<category><![CDATA[Efficient Learning to Code]]></category>
		<category><![CDATA[puzzle-based learning]]></category>
		<category><![CDATA[Python 3]]></category>
		<category><![CDATA[Python puzzle]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=493</guid>

					<description><![CDATA[<p>A code puzzle is an educative snippet of source code that teaches a single computer science concept by activating the learner's curiosity and involving them in the learning process.</p>
<p>The post <a href="https://blog.finxter.com/10-reasons-why-solving-code-puzzles-makes-you-smarter/">10 Reasons Why Solving Code Puzzles Makes You Smarter</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this post, I will give you 10 reasons for puzzle-based learning. There is robust evidence in psychological science for each of these reasons. Yet, no existing learning system lifts code puzzles to first-class citizens. To change that, I developed the <a href="http://finxter.com" target="_blank" rel="noreferrer noopener">Finxter App</a> and published the programming textbook<a href="https://blog.finxter.com/coffee-break-python" target="_blank" rel="noreferrer noopener"> &#8220;Coffee Break Python: 50 Workouts to Kickstart Your Rapid Code Understanding in Python&#8221;</a>. In brief, these are the 10 reasons for puzzle-based learning:</p>



<h2 class="wp-block-heading">1. Overcome the Knowledge Gap</h2>



<p>The great teacher Socrates delivered complex knowledge by asking a sequence of questions. Each question built on answers to previous questions provided by the student. This more than 2400 year old teaching technique is still in widespread use today. A good teacher opens a gap between their knowledge and the learner’s. This knowledge gap makes the learner aware that they do not know the answer to a burning question. This creates a tension in the learner’s mind. To close this gap, the learner awaits the missing piece of knowledge from the teacher. Better yet, the learner starts developing their own answers. The learner craves knowledge.</p>



<figure class="wp-block-image"><img decoding="async" src="https://images.pexels.com/photos/161275/santorini-travel-holidays-vacation-161275.jpeg?auto=compress&amp;cs=tinysrgb&amp;h=650&amp;w=940" alt="Santorinni Greece during Daytime"/></figure>



<p>Code puzzles open an immediate knowledge gap. When looking at the code, you first do not understand what the puzzle means. The puzzle’s semantics are hidden. But only you can transform the unsolved puzzle into a solved one. Look at this riddle:</p>



<p><strong>“What pulls you down and never lets go?” </strong></p>



<p>Can you feel the tension? Opening and closing a knowledge gap is a very powerful method for effective learning.</p>



<p>(By the way, the answer is <em>Gravity</em>.)</p>



<p>Bad teachers open a knowledge gap that is too large. The learner feels frustrated because they cannot overcome the gap. Suppose you are standing before a river that you must cross. But you have not learned to swim, yet. Now, consider two rivers. The first river is the Colorado River that carved out the Grand Canyon–quite a gap. The second river is Rattlesnake Creek. The fact that you have never heard of this river indicates that it is not too big of an obstacle. Most likely, you will not even attempt to swim through the big Colorado River. But you could swim over the Rattlesnake if you stretch your abilities just a little bit. You will focus, pep-talk yourself, and overcome the obstacle. As a result, your swimming skills and your confidence will grow a little bit.</p>



<p>Puzzles are like the Rattlesnake–they are not too great a challenge. You must stretch yourself to solve them, but you can do it if you go all-out.</p>



<p>Constantly feeling a small but non-trivial knowledge gap creates a healthy learning environment. Stretch your limits, overcome the knowledge gap, and become better–one puzzle at a time.</p>



<h2 class="wp-block-heading">2. Embrace the Eureka Moment</h2>



<p>Humans are unique because of their ability to learn. Fast and thorough learning has always increased our chances of survival. Thus, evolution created a brilliant biological reaction to reinforce learning in your body.</p>



<p>Your brain is wired to seek new information; it is wired to always process data, to always learn.</p>



<figure class="wp-block-image"><img decoding="async" src="https://images.pexels.com/photos/160914/smile-man-worker-vertical-160914.jpeg?auto=compress&amp;cs=tinysrgb&amp;h=650&amp;w=940" alt="Men's Gray Crew Neck Shirt"/></figure>



<p>Did you ever feel the sudden burst of happiness after experiencing a eureka moment? Your brain releases endorphins, the moment you close a knowledge gap. The instant gratification from learning is highly addictive, but this addiction makes you smarter. Solving a puzzle gives your brain instant gratification. Easy puzzles open small, hard puzzles, which open large knowledge gaps. Overcome any of them and learn in the process.</p>



<h2 class="wp-block-heading">3. Divide and Conquer</h2>



<p>Learning to code is a complex task. You must learn a myriad of new concepts and language features. Many aspiring coders are overwhelmed by the complexity. They seek a clear path to mastery.</p>



<figure class="wp-block-image"><img decoding="async" src="https://images.pexels.com/photos/249798/pexels-photo-249798.png?auto=compress&amp;cs=tinysrgb&amp;h=650&amp;w=940" alt="Full Frame Shot of Abstract Pattern"/></figure>



<p>People tend to prioritize specific activities with clearly defined goals. If the path is not clear, we tend to drift away toward more specific paths.<br>Most aspiring coders think they have a goal: becoming a better coder. Yet, this is not a specific goal at all. So what is a specific goal? Unfortunately for many of us, the goal <em>“Watching Game of Thrones after dinner, Series 2 Episode 1”</em> is as specific as it can be. Due to the specificity, watching Netflix is more powerful than the fuzzy path of learning to code. Hence, watching Netflix wins the battle for attention too often.</p>



<p>As any productivity expert tells you: break a big task or goal into a series of smaller steps. Finishing each tiny step brings you one step closer to your big goal. <em>Divide and conquer</em> makes you feel in control, pushing you one step closer toward mastery. You want to become a master coder? Break the big coding skill into a list of sub-skills–understanding language features, designing algorithms, reading code–and then tackle each sub-skill one at a time.</p>



<p>Code puzzles do this for you. They break up the huge task of learning to code into a series of smaller learning units. The student experiences laser focus on one learning task such as <em>recursion</em>, the <em>for loop</em>, or <em>keyword arguments</em>. Don’t worry if you do not understand these concepts yet–after working through this book, you will. A good code puzzle delivers a single idea from the author’s into the student’s head. You can digest one puzzle at a time. Each puzzle is a step toward your bigger goal of mastering computer science. Keep solving puzzles and you keep improving your skills.</p>



<h2 class="wp-block-heading">4. Improve From Immediate Feedback</h2>



<p>As a child, you learned to walk by trial and error–try, receive feedback, adapt, and repeat. Unconsciously, you will minimize negative and maximize positive feedback. You avoid falling because it hurts, and you seek the approval of your parents. But not only organic life benefits from the great learning technique of trial and error. In machine learning, algorithms learn by guessing an output and adapting their guesses based on their correctness. To learn anything, you need feedback such that you can adapt your actions.</p>



<figure class="wp-block-image"><img decoding="async" src="https://images.pexels.com/photos/1120106/pexels-photo-1120106.jpeg?auto=compress&amp;cs=tinysrgb&amp;h=650&amp;w=940" alt="Girl Wearing White Clothes Walking on Pavement Road"/></figure>



<p>However, an excellent learning environment provides you not only with feedback but with <em>immediate</em> feedback for your actions. In contrast, poor learning environments do not provide any feedback at all or only with a large delay. Examples are activities with good short-term and bad long-term effects such as smoking, alcohol, or damaging the environment. People cannot control these activities because of the delayed feedback. If you were to slap your friend each time he lights a cigarette–a not overly drastic measure to safe his life–he would quickly stop smoking. If you want to learn fast, make sure that your environment provides immediate feedback. Your brain will find rules and patterns to maximize the reinforcement from the immediate feedback.</p>



<p><a href="https://finxter.com" target="_blank" rel="noreferrer noopener">The Finxter App </a>offers you an environment with immediate feedback to make learning to code easy and fast. Over time, your brain will absorb the meaning of a code snippet quicker and with higher precision this way. Learning this skill pushes you toward the top 10% of all coders. There are other environments with immediate feedback, like executing code and checking correctness, but puzzle-based learning is the most direct one: Each puzzle educates with immediate feedback.</p>



<h2 class="wp-block-heading">5. Measure Your Skills</h2>



<p>You need to have a definite goal to be successful. A definite goal is a powerful motivator and pushes you to stretch your skills constantly. The more definite and concrete it is, the stronger it becomes. Holding a definite goal in your mind is the first and foremost step toward its physical manifestation. Your beliefs bring your goal into reality.</p>



<p>Think about an experienced Python programmer you know, e.g., your nerdy colleague or class mate. How good are their Python skills compared to yours? On a scale from your grandmother to Bill Gates, where is your colleague and where are you? These questions are difficult to answer because there is no simple way to measure the skill level of a programmer.<br>This creates a severe problem for your learning progress: the concept of being a good programmer becomes fuzzy and diluted. What you can’t measure, you can’t improve. Not being able to measure your coding skills diverts your focus from systematic improvement. Your goal becomes less definite.</p>



<figure class="wp-block-image"><img decoding="async" src="https://images.pexels.com/photos/88733/pexels-photo-88733.jpeg?auto=compress&amp;cs=tinysrgb&amp;h=650&amp;w=940" alt="Red Pencil on Gold Metal Rulers"/></figure>



<p>So what should be your definite goal when learning a programming language? To answer this, let us travel briefly to the world of chess, which happens to provide an excellent learning environment for aspiring players. Every player has an <a href="https://en.wikipedia.org/wiki/Elo_rating_system">Elo rating</a> number that measures their skill level. You get an Elo rating when playing against other players–if you win, your Elo rating increases. Victories against stronger players lead to a higher increase of the Elo rating. Every ambitious chess player simply focuses on one thing: increasing their Elo rating. The ones that manage to push their Elo rating very high, earn grand master titles. They become respected among chess players and in the outside world.</p>



<p>Every chess player dreams of being a grandmaster. The goal is as definite as it can be: reaching an Elo of 2400 and master level. Thus, chess is a great learning environment–every player is always aware of their skill level. A player can measure how decisions and habits impact their Elo number. Do they improve when sleeping enough before important games? When training opening variants? When solving chess puzzles? What you can measure, you can improve.</p>



<p>The main idea of our book <a href="https://www.amazon.com/dp/B07GSTJPFD">Coffee Break Python</a>, and the associated <a href="http://finxter.com">learning app</a>, is to transfer this method of measuring skills from the chess world to programming. Suppose you want to learn Python. The Finxter website assigns you a rating number that measures your coding skills. Every Python puzzle has a rating number as well, according to its difficulty level. You <em>play </em>against a puzzle at your difficulty level: The puzzle and you will have more or less the same Elo rating so that you can enjoy personalized learning. If you solve the puzzle, your Elo increases and the puzzle’s Elo decreases. Otherwise, your Elo decreases and the puzzle’s Elo increases. Hence, the Elo ratings of the difficult puzzles increase over time. But only learners with high Elo ratings will see them. This self-organizing system ensures that you are always challenged but not overwhelmed, while you constantly receive feedback about how good your skills are in comparison with others. You always know exactly where you stand on your path to mastery.</p>



<h2 class="wp-block-heading">6. Individualized Learning</h2>



<p>The educational system today is built around the idea of classes and courses. In these environments, all students consume the same learning material from the same teacher applying the same teaching methods.<br>This traditional idea of classes and courses has a strong foundation in our culture and social thinking patterns. Yet, science proves again and again the value of individualized learning. Individualized learning tailors the content, pace, style, and technology of teaching to the student’s skills and interests. Of course, truly individualized learning has always required a lot of teachers. But paying a high number of teachers is expensive (at least in the short term) in a non-digital environment.</p>



<figure class="wp-block-image"><img decoding="async" src="https://images.pexels.com/photos/1209843/pexels-photo-1209843.jpeg?auto=compress&amp;cs=tinysrgb&amp;h=650&amp;w=940" alt="Person With Body Painting"/></figure>



<p>In the digital era, many fundamental limitations of our society begin to crack.<br>Compute servers and intelligent machines can provide individualized learning with ease. But with changing limitations, we must adapt our thinking as well.<br>Machines will enable truly individualized learning very soon; yet society needs time to adapt to this trend.</p>



<p>Puzzle-based learning is a perfect example of automated, individualized learning. The ideal puzzle stretches the student’s abilities and is neither boring nor overwhelming. Finding the perfect learning material for each learner is an important and challenging problem. Finxter uses a simple but effective solution to solve this problem: the Elo rating system. The student solves puzzles at their individual skill level. Our <a href="https://www.amazon.com/dp/B07GSTJPFD">programming textbook “Coffee Break Python”</a> and the book’s web backend <a href="http://Finxter.com">Finxter </a>pushes teaching toward individualized learning.</p>



<h2 class="wp-block-heading">7. Small is Beautiful</h2>



<p>The 21st century has seen a rise in microcontent. Microcontent is a short and accessible piece of valuable information such as the weather forecast, a news headline, or a cat video. Social media giants like Facebook and Twitter offer a stream of never-ending microcontent. Microcontent is powerful because it satisfies the desire for shallow entertainment. Microcontent has many benefits: the consumer stays engaged and interested, and it is easily digestible in a short time. Each piece of microcontent pushes your knowledge horizon a bit further. Today, millions of people are addicted to microcontent.</p>



<p>However, this addiction will also become a problem to these millions. The computer science professor Cal Newport shows in his book <em>“Deep Work”</em> that modern society values deep work more than shallow work. Deep work is a high-value activity that needs intense focus and skill. Examples of deep work are programming, writing, or researching. Contrarily, shallow work is every low-value activity that can be done by everybody (e.g., posting the cat videos to social media). The demand for deep work grew with the rise of the information society; at the same time, the supply stayed constant or decreased, e.g., because of the addictiveness of shallow social media. People that see and understand this trend can benefit tremendously. In a free market, the prices of scarce and demanded resources rise. Because of this, surgeons, lawyers, and software developers earn $100,000 per year and more. Their work cannot easily be replaced or outsourced to unskilled workers. If you are able to do deep work, to focus your attention on a challenging problem, society pays you generously.</p>



<figure class="wp-block-image"><img decoding="async" src="https://images.pexels.com/photos/372281/pexels-photo-372281.jpeg?auto=compress&amp;cs=tinysrgb&amp;h=650&amp;w=940" alt="adult, Asian, bald"/></figure>



<p><strong>What if we could marry the concepts of microcontent and deep work? </strong></p>



<p>This is the promise of puzzle-based learning. Finxter offers a stream of self-contained microcontent in the form of hundreds of small code puzzles. But instead of just being unrelated microcontent, each puzzle is a tiny stimulus that teaches a coding concept or language feature. Hence, each puzzle pushes your knowledge <em>in the same direction</em>.</p>



<p>Puzzle-based learning breaks the bold goal, i.e., <strong>reach the mastery level in Python</strong>, into tiny actionable steps: solve and understand one code puzzle per day. While solving the smaller tasks, you progress toward your larger goal.<br>You take one step at a time to eventually reach the mastery level.</p>



<p>A clear path to success.</p>



<h2 class="wp-block-heading">8. Active Beats Passive Learning</h2>



<p>Robust scientific evidence shows that active learning doubles students’ learning performance. In a <a href="https://en.wikipedia.org/wiki/Active_learning#Research_evidence">study </a>on that matter, test scores of active learners improve by more than one grade compared to their passive learning fellow students. Not using active learning techniques wastes your time and hinders you in reaching your full potential in any area of life. Switching to active learning is a simple tweak that will instantly improve your performance when learning any subject.</p>



<figure class="wp-block-image"><img decoding="async" src="https://images.pexels.com/photos/159823/kids-girl-pencil-drawing-159823.jpeg?auto=compress&amp;cs=tinysrgb&amp;h=350" alt="Girls on Desk Looking at Notebook"/></figure>



<p><strong>How does active learning work?</strong></p>



<p>Active learning requires the student to interact with the material, rather than simply consuming it. It is student- rather than teacher-centric. Great active learning techniques are asking and answering questions, self-testing, teaching, and summarizing. A popular study shows that one of the best learning techniques is <a href="http://journals.sagepub.com/doi/abs/10.1177/1529100612453266" target="_blank" rel="noreferrer noopener">practice testing</a>. In this learning technique, you test your knowledge even if you have not learned everything yet. Rather than <em>“learning by doing”</em>, it’s “<em>learning by testing”</em>.</p>



<p>However, the study argues that students must feel safe during these tests. Therefore, the tests must be low-stake, i.e., students have little to lose. After the test, students get feedback about the correctness of the tests. The study shows that practice testing boosts long-term retention of the material by almost a factor of 10. As it turns out, solving a daily code puzzle is not just another learning technique–it is one of the best.</p>



<p>Although active learning is twice as effective, most books focus on passive learning. The author delivers information; the student passively consumes the information. Some programming books include active learning elements by adding tests or by asking the reader to try out the code examples. Yet, I always found this impracticable while reading on the train, on the bus, or in bed. But if these active elements drop out, learning becomes 100% passive again.</p>



<p>Fixing this mismatch between research and common practice drove me to write this book about puzzle-based learning. In contrast to other books, <a href="https://www.amazon.com/dp/B07GSTJPFD" target="_blank" rel="noreferrer noopener">our programming textbook makes active learning a first-class citizen</a>. Solving code puzzles is an inherent active learning technique. You must develop the solution yourself, in every single puzzle. The teacher is as much in the background as possible–they only explain the correct solution if you couldn’t work it out yourself. But before telling you the correct solution, your knowledge gap is already ripped wide open. Thus, you are mentally ready to digest new material.</p>



<p>To drive this point home, let me emphasize this argument again: puzzle-based learning is a variant of the active learning technique named practice testing. Practice testing is scientifically proven to teach you more in less time.</p>



<h2 class="wp-block-heading">9. Make Source Code a First-class Citizen</h2>



<p>Each grandmaster of chess has spent tens of thousands of hours looking into a near infinite number of chess positions. Over time, they develop a powerful skill: the intuition of the expert. When presented with a new position, they are able to name a small number of strong candidate moves within seconds. They operate on a higher level than normal people. For normal people, the position of a single chess piece is one chunk of information. Hence they can only memorize the position of about six chess pieces. But chess grand masters view a whole position or a sequence of moves as a single chunk of information. The extensive training and experience has burned strong patterns into their biological neural networks. Their brain is able to hold much more information–a result of the good learning environment they have put themselves in.</p>



<p><strong>What are some principles of good learning? </strong></p>



<p>Let us dive into another example of a great learning environment–this time for machines. Recently, Google’s artificial intelligence AlphaZero has proven to be the best chess playing entity in the world. AlphaZero uses artificial neural networks. An artificial neural network is the digital twin of the human brain with artificial neurons and synapses. It learns by example much like a grandmaster of chess. It presents itself a position, predicts a move, and adapts its prediction to the extent the prediction was incorrect.</p>



<p>Chess and machine learning exemplify principles of good learning that are valid in any field you want to master. First, transform the object to learn into a stimulus that you present to yourself over and over again. In chess, study as many chess positions as you can. In math, make reading mathematical papers with theorems and proofs a habit. In coding, expose yourself to lots of code. Second, seek feedback. Immediate feedback is better than delayed feedback. However, delayed feedback is still much better than no feedback at all. Third, take your time to learn and understand thoroughly. Although it is possible to learn on-the-go, you will cut corners. The person who prepares beforehand always has an edge. In the world of coding, some people recommend learning by coding practical projects and doing nothing more. Chess grandmasters, sports stars, and intelligent machines do not follow this advice. They learn by practicing isolated stimuli again and again until they have mastered them. Then they move on to more complex stimuli.</p>



<figure class="wp-block-image"><img decoding="async" src="https://images.pexels.com/photos/169573/pexels-photo-169573.jpeg?auto=compress&amp;cs=tinysrgb&amp;h=650&amp;w=940" alt="Grayscale Photo of Computer Laptop Near White Notebook and Ceramic Mug on Table"/></figure>



<p>Puzzle-based learning is code-centric. You will find yourself staring at the code for a long time until the insight strikes. This creates new synapses in your brain that help you understand, write, and read code fast. Placing code in the center of the whole learning process creates an environment in which you will develop the powerful intuition of the expert.</p>



<p><strong>Maximize the learning time you spend looking at code rather than at other stimuli.</strong></p>



<h2 class="wp-block-heading">10. What You See is All There is</h2>



<p>My professor of theoretical computer science used to tell us that if we only stare long enough at a proof, the meaning will transfer into our brains by osmosis. This fosters deep thinking, a state of mind where learning is more productive. In my experience, his staring method works—but only if the proof contains everything you need to know to solve it. It must be self-contained.</p>



<p>A good code puzzle beyond the most basic level is self-contained. You can solve it purely by staring at it until your mind follows your eyes—your mind develops a solution based on rational thinking. There is no need to look things up. If you are a great programmer, you will find the solution quickly. If not, it will take more time but you can still find the solution—it is just more challenging.</p>



<p>My gold standard was to design each puzzle such that it is mostly self-contained. However, to deliver on the book’s promise of training your understanding of the Python basics, puzzles must introduce syntactical language elements as well. But even if the syntax in a puzzle challenges you, you should still develop your own solutions based on your imperfect knowledge. This probabilistic thinking opens the knowledge gap and prepares your brain to receive and digest the explained solution. After all, your goal is long-term retention of the material.</p>


<div class="wp-block-image">
<figure class="aligncenter is-resized"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2018/08/3D_Version1-1024x944.jpg" alt="Coffee Break Python" width="256" height="236"/></figure>
</div>


<div class="wp-block-button aligncenter"><a class="wp-block-button__link has-vivid-red-background-color has-background wp-element-button" href="https://www.booklinker.net/book-links.php" target="_blank" rel="noreferrer noopener">Buy Book</a></div>



<p>What do you think of puzzle-based learning? Please share your thoughts and leave a comment below.</p>
<p>The post <a href="https://blog.finxter.com/10-reasons-why-solving-code-puzzles-makes-you-smarter/">10 Reasons Why Solving Code Puzzles Makes You Smarter</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.finxter.com/10-reasons-why-solving-code-puzzles-makes-you-smarter/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-06-26 19:01:41 by W3 Total Cache
-->