<?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>Francesc Serrano, Author at Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/author/francescserrano/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/author/francescserrano/</link>
	<description></description>
	<lastBuildDate>Tue, 09 Feb 2021 10:03:56 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>Francesc Serrano, Author at Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/author/francescserrano/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Switch Keys and Values in a Python Dictionary?</title>
		<link>https://blog.finxter.com/how-to-switch-keys-and-values-in-a-python-dictionary/</link>
		
		<dc:creator><![CDATA[Francesc Serrano]]></dc:creator>
		<pubDate>Tue, 09 Feb 2021 09:45:39 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Dictionary]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=23439</guid>

					<description><![CDATA[<p>Problem:&#160;Given a dictionary in Python; how to switch Keys and Values?&#160; Method 1: Using&#160;a for loop&#160;&#160; Method 2: Using the zip function Method 3: Using the map and reverse functions Method 4: Using a dictionary comprehension Summary:&#160;Use one of the following methods to switch between the keys and values in a dictionary with unique values. ... <a title="How to Switch Keys and Values in a Python Dictionary?" class="read-more" href="https://blog.finxter.com/how-to-switch-keys-and-values-in-a-python-dictionary/" aria-label="Read more about How to Switch Keys and Values in a Python Dictionary?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-switch-keys-and-values-in-a-python-dictionary/">How to Switch Keys and Values in a Python Dictionary?</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="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong>Problem:&nbsp;</strong>Given a <a href="https://blog.finxter.com/python-dictionary/" target="_blank" rel="noreferrer noopener" title="Python Dictionary – The Ultimate Guide">dictionary </a>in Python; how to switch Keys and Values?&nbsp;</p>



<ul class="wp-block-list"><li>Method 1: Using&nbsp;a <a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops"><code>for</code> loop</a>&nbsp;&nbsp;</li><li>Method 2: Using the <a href="https://blog.finxter.com/python-ziiiiiiip-a-helpful-guide/" target="_blank" rel="noreferrer noopener" title="Python Zip — A Helpful Illustrated Guide"><code>zip</code> </a>function</li><li>Method 3: Using the <a href="https://blog.finxter.com/python-map/" target="_blank" rel="noreferrer noopener" title="Python map() — Finally Mastering the Python Map Function [+Video]"><code>map</code> </a>and <a href="https://blog.finxter.com/python-list-reverse/" target="_blank" rel="noreferrer noopener" title="Python List reverse()"><code>reverse</code> </a>functions</li><li>Method 4: Using a <a href="https://blog.finxter.com/python-dictionary-comprehension/" target="_blank" rel="noreferrer noopener" title="Python Dictionary Comprehension: A Powerful One-Liner Tutorial">dictionary comprehension</a></li></ul>



<p class="wp-block-paragraph"><strong>Summary:&nbsp;</strong>Use one of the following methods to switch between the keys and values in a dictionary with unique values.</p>



<p class="wp-block-paragraph">Imagine you in the morning, on your desktop, with your coffee and your laptop in front of you. You feel relaxed, comfortable, sure about yourself and ready for another amazing day doing what you love the most. To solve problems with your brain and your fingers using the potential that Python offers to you!</p>



<p class="wp-block-paragraph">Then your boss arrives and looking into your eyes he says: “Look, we have a problem and I need you to fix it. You have 1 hour to give me a solution that we can replicate for all the files we have in the company or we are all fired”</p>



<p class="wp-block-paragraph">Your boss is a nice person. He gives you this example to start with:&nbsp;</p>



<pre class="wp-block-preformatted"># Input ? &nbsp;&nbsp;&nbsp; {'a': 1, 'b': 2, 'c': 3, 'd': 4}</pre>



<pre class="wp-block-preformatted"># Output ?&nbsp;&nbsp;&nbsp; {1: 'a', 2: 'b', 3: 'c', 4: 'd'}</pre>



<p class="wp-block-paragraph">In this article, we will show you four methods to accomplish this. The most Pythonic one is <strong>Method 4</strong>&#8212;so, if you&#8217;re short on time, go to <strong>Method 4</strong> right away!</p>



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



<p class="wp-block-paragraph">If you are an experienced Python developer, you probably have a solid base of all kind of data structures. If so, just skip ahead and go to <strong>Method 1</strong>. On the other hand, if you are new to this topic or you want to refresh this data type, I invite you to read these lines below. As a Python developer, it is important to gain knowledge and build a solid foundation in <a href="https://docs.python.org/3/tutorial/datastructures.html" target="_blank" rel="noreferrer noopener">data structures</a>.&nbsp;</p>



<p class="wp-block-paragraph">In this article we are going to talk about how to revert one of the most useful structures any Python developer has to master, this is the <strong>dictionary</strong>.&nbsp;</p>



<p class="wp-block-paragraph"><strong><em>But what is it a dictionary?</em></strong></p>



<p class="wp-block-paragraph">A dictionary is a data structure formed by a set of <strong>key : value</strong> pairs.&nbsp;</p>



<p class="wp-block-paragraph">The syntax 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="">{'key1': 'value1', 'key2': 'value2', 'key3': 'value3',}</pre>



<p class="wp-block-paragraph">It also can be represented like this for easy reading:</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="">{
    'key1': 'value1', 
    'key2': 'value2', 
    'key3': 'value3',
}
</pre>



<p class="has-cyan-bluish-gray-background-color has-background wp-block-paragraph"><strong>Note</strong>: The last comma after <code>value3</code> it is not necessary, indeed. But I recommend you to get this it as a habit and write it always. It will save you time by avoiding unwanted bugs in your future clean code <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>



<p class="wp-block-paragraph">The key can be any kind of <a href="https://blog.finxter.com/how-to-check-if-an-object-is-of-type-list-in-python/" target="_blank" rel="noreferrer noopener" title="How to Check if an Object is of Type List in Python?">type</a>, but what is important to highlight here is that:</p>



<ul class="wp-block-list"><li>The key has to be <strong>Unique</strong> in the whole dictionary. If not the last duplicated key will override the defined previous one</li></ul>



<p class="wp-block-paragraph">Example of a dictionary with an integer as a key:</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: 100, 2: 200}</pre>



<p class="wp-block-paragraph">Example of a dictionary with a float as a key:</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.0: 100, 2.3: 200}</pre>



<p class="wp-block-paragraph">Example of a dictionary with string as a key:</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': 100, 'b': 200}</pre>



<p class="wp-block-paragraph">Example of a dictionary with a tuple as a key:</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="">{(0, 0): 100, (1, 1): 200}
 
#or
 
{('Harry','Potter') : 100, ('Hermione','Granger') : 200}
</pre>



<p class="has-cyan-bluish-gray-background-color has-background wp-block-paragraph"><strong>Note</strong>: Although you can use a float as a key, it is not very recommendable because if you define 1.0 and 1 the last key will override the first key. </p>



<p class="wp-block-paragraph">Here you have an example:</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.0: 100, 1: 200} ? {1.0: 200}</pre>



<ul class="wp-block-list"><li>It has to be <strong>Immutable</strong>. That means that the key can be an integer, a float, a boolean, a string or even a <a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide To Python Tuples">tuple </a>among others, but never a <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">list </a>or another dictionary as these data structures are mutable ( <a href="https://blog.finxter.com/the-mutable-default-argument-in-python/" target="_blank" rel="noreferrer noopener">If you need to dig more about this concept I suggest you read this article about mutable or immutable objects</a>).&nbsp;</li></ul>



<h2 class="wp-block-heading">Method 1: Using&nbsp;a for loop approach</h2>



<p class="wp-block-paragraph">The easiest solution and the typical one that any developer may discover at first would be to use the structure “for loop” to perform a definite iteration to accomplish the task.</p>



<p class="wp-block-paragraph">The python for loop is represented by a variable, an iterable, and some statements.&nbsp;</p>



<p class="wp-block-paragraph">The syntax is:&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="">for &lt;var> in &lt;iterable>:
    &lt;statement(s)>
</pre>



<p class="wp-block-paragraph">Knowing this structure we could have a first valid approach to the solution:&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="">my_dict = {'a': 1, 'c': 3, 'b': 2, 'd': 4}
new_dict = {}
for k, v in my_dict.items():
    new_dict[v] = k
</pre>



<p class="wp-block-paragraph">Output:</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: 'a', 2: 'b', 3: 'c', 4: 'd'}</pre>



<p class="wp-block-paragraph">Explanation:</p>



<ol class="wp-block-list"><li>In the above code, we need to <a href="https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects" target="_blank" rel="noreferrer noopener">create</a> a new instance of a dictionary using the expression <code>{}</code> and assigned it to a new variable called <code>new_dict</code>.&nbsp;</li></ol>



<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 = {}</pre>



<ol class="wp-block-list" start="2"><li>Then we use the “for loop” to iterate the keys and values of the dictionary.</li></ol>



<ol class="wp-block-list"><li><code>k,v</code> are the variables. The key and values</li><li><code>my_dict</code> is the iterable data structure that can be a dictionary, a list, or a tuple. In this case, we need to add the method .items() that returns a list of (key, value) tuple pairs. <code>my_dict.items</code> returns:</li></ol>



<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_items([('a', 1), ('b', 2), ('c', 3)])</pre>



<ol class="wp-block-list" start="3"><li><code>new_dict[v] = k</code> is the statement where we switch the values of the dictionary. </li></ol>



<h2 class="wp-block-heading">Method 2: Using&nbsp;the zip function</h2>



<p class="wp-block-paragraph">Another possible solution would be using the <code><a href="https://blog.finxter.com/python-ziiiiiiip-a-helpful-guide/" title="Python Zip — A Helpful Illustrated Guide">zip</a></code> function. </p>



<p class="wp-block-paragraph">The syntax 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="">zip(*iterables)</pre>



<p class="wp-block-paragraph">But how does it work?</p>



<p class="wp-block-paragraph">Well, the <code>zip</code> function returns an object created from some iterators given as parameters. These iterators can be lists, but they must have the same number of items each. This is to assure the proper <a href="https://blog.finxter.com/how-to-use-pythons-join-function-on-a-list-of-objects-rather-than-strings/" target="_blank" rel="noreferrer noopener" title="How to Use Python’s Join() on a List of Objects (Not Strings)?">join </a>between the items. Here you can see an example:</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="">#iterable 1 = ['one', 'two', 'three']
#iterable  = [1, 2, 3]
 
zip(['one', 'two', 'three'], [1, 2, 3])
 
#result: [('one', 1), ('two', 2), ('three', 3)]
</pre>



<p class="wp-block-paragraph">So at this point, the solution for the second method would be:</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 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
 
dict(zip(my_map.values(), my_map.keys()))
</pre>



<p class="wp-block-paragraph">Output:</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: 'a', 2: 'b', 3: 'c', 4: 'd'}</pre>



<p class="wp-block-paragraph">Explanation:</p>



<p class="wp-block-paragraph">The idea behind this solution is to provide to the zip function 2 iterables, actually 2 lists, in this case, to create a unique <a href="https://blog.finxter.com/how-to-sort-a-list-of-tuples-most-pythonic-way/" target="_blank" rel="noreferrer noopener" title="How to Sort a List of Tuples? – Most Pythonic Way!">list of tuples</a>. The trick here is to use the keys as values and vice versa by using the form <code>my_dict.values()</code> to obtain the values and <code>my_dict.keys()</code> to obtain the keys in two separated lists. </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 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

my_dict.values()
# [1, 2, 3, 4] 

my_dict.keys()
# ['a', 'c', 'c', 'd']</pre>



<ol class="wp-block-list"><li>Once this is accomplished if we use the zip function we will have:</li></ol>



<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="">zip(my_map.values(), my_map.keys())
# [(1, 'a'), (2, 'b'), (3, 'c'),  (4, 'd')]
</pre>



<ol class="wp-block-list" start="2"><li>At this point the only we need to create a dictionary using the type constructor <code><a href="https://blog.finxter.com/python-dict/" target="_blank" rel="noreferrer noopener" title="Python dict() — A Simple Guide with Video">dict()</a></code> and obtaining the result we were looking for:</li></ol>



<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(zip(my_map.values(), my_map.keys()))</pre>



<h2 class="wp-block-heading">Method 3: Using&nbsp;the map and reverse functions&nbsp;</h2>



<p class="wp-block-paragraph">The third solution you can think of is using the <code><a href="https://blog.finxter.com/python-map/" target="_blank" rel="noreferrer noopener" title="Python map() — Finally Mastering the Python Map Function [+Video]">map</a></code> and <code><a href="https://blog.finxter.com/python-list-reverse/" target="_blank" rel="noreferrer noopener" title="Python List reverse()">reverse</a></code> function together with the constructor <code>dict()</code>.</p>



<p class="wp-block-paragraph">But how does it work and how do we use these two functions exactly? Let’s have a look at them both to understand it.</p>



<p class="wp-block-paragraph"><strong><em>Reversed Function:</em></strong></p>



<p class="wp-block-paragraph">The reversed function has the property to return an iterator in the reversed order of a sequence given. It is important to mark that <code><a href="https://blog.finxter.com/python-built-in-functions/" target="_blank" rel="noreferrer noopener" title="Python Built-In Functions">reversed()</a></code> just accepts sequences and not any other kind of iterators. So in case you want to reverse an iterator you should consider to transform it previously to a list.  </p>



<p class="wp-block-paragraph">The syntax 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="">reversed(seq)</pre>



<p class="wp-block-paragraph">Examples:</p>



<p class="wp-block-paragraph">string sequence: </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="">seq = 'retxnif'

reversed(seq)
# &lt;reversed object at 0x0000000002A41AC8>

list(reversed(seq)) 
# ['f', 'i', 'n', 'x', 't', 'e', 'r']</pre>



<p class="wp-block-paragraph">list sequence:</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="">seq = ['r', 'e', 't', 'x', 'n', 'i', 'f']

reversed(seq)
# &lt;listreverseiterator object at 0x0000000002A41AC8>

list(reversed(seq))
# ['f', 'i', 'n', 'x', 't', 'e', 'r'] </pre>



<p class="wp-block-paragraph"><a href="https://blog.finxter.com/python-tuple/" target="_blank" rel="noreferrer noopener" title="Python tuple() — A Simple Guide with Video">tuple </a>sequence:</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="">seq = ('r', 'e', 't', 'x', 'n', 'i', 'f')

reversed(seq)
# &lt;reversed object at 0x0000000002AB2C48>

list(reversed(seq))
# ['f', 'i', 'n', 'x', 't', 'e', 'r']</pre>



<p class="wp-block-paragraph"><a href="https://blog.finxter.com/python-range-function/" target="_blank" rel="noreferrer noopener" title="Python range() Function — A Helpful Illustrated Guide">range </a>sequence</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="">seq = range(5)
#  [0, 1, 2, 3, 4]

reversed(seq) 
# &lt;listreverseiterator object at 0x0000000002A41AC8>

list(reversed(seq))
# [4, 3, 2, 1, 0]</pre>



<p class="wp-block-paragraph">Probably if you have read the <a href="https://blog.finxter.com/free-book-coffee-break-python-slicing/" target="_blank" rel="noreferrer noopener" title="Free Book Coffee Break Python Slicing"><strong>Coffee Break Python Slicing</strong></a> from Chris you would notice that the last case could be achieved by <code>range(5)[::-1]</code>. However, it seems from the documentation that <code>reversed(seq)</code> is faster and use less memory. So keep it in mind.</p>



<h3 class="wp-block-heading">Map Function</h3>



<p class="wp-block-paragraph">To comprehend the map function, first, we need to understand what mapping means. When we use the map, what we are after is to produce a new iterable from the original one by applying a transformational function to each item of it.&nbsp;</p>



<p class="wp-block-paragraph">In other words, is a way to process iterables without the need of a <a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops">loop</a>. </p>



<p class="wp-block-paragraph">The syntax 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="">map(function, iterable, ...)</pre>



<ul class="wp-block-list"><li><code>function</code>: is the function that will be applied to every item of the iterable</li><li><code>iterable</code>: is the parameter that is going to be mapped. It can be a list, tuple, etc.</li></ul>



<p class="wp-block-paragraph">Example:</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="">#transform all the items of a string to a integer
iterable_str = ['1','2','3','4','5']
map(int,iterable_str) 
# [1, 2, 3, 4, 5]
</pre>



<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="">#transform all the items of a string to a float
iterable_str = ['1.0','2.0','3.0','4.0','5.0']
map(float,iterable_str) 
# [1.0, 2.0, 3.0, 4.0, 5.0]
</pre>



<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="">#transform all the items of a string by applying strings methods like capitalize
iterable_str =['finxter','is','an','endless','source','of','knowledge']
list(map(str.capitalize, iterable_str)) 
# ['Finxter', 'Is', 'An', 'Endless', 'Source', 'Of', 'Knowledge']
</pre>



<p class="wp-block-paragraph">So now that we know the theory behind these two functions we could conclude that an acceptable solution by joining them would be this one:</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 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
dict(map(reversed, my_dict.items())
# {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
</pre>



<p class="wp-block-paragraph">At this point, you could fairly think that finally, you have the right and the most pythonic solution, don’t you? Well, no… so here it comes the 4<sup>th</sup> method to provide you with more knowledge. So, keep reading!&nbsp;</p>



<h2 class="wp-block-heading">Method 4: Using a dictionary comprehension</h2>



<p class="wp-block-paragraph">Although functional programming tools like <code>map()</code> have been very useful in the past being fundamental components in python since more than 20 years, nowadays there are other forms that are becoming more popular among Python developers like <a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener" title="List Comprehension in Python — A Helpful Illustrated Guide">list comprehension</a> or <a href="https://blog.finxter.com/python-dictionary-comprehension/" target="_blank" rel="noreferrer noopener" title="Python Dictionary Comprehension: A Powerful One-Liner Tutorial">dictionary comprehension</a>.</p>



<p class="wp-block-paragraph"><strong><em>How do they work?&nbsp;</em></strong></p>



<p class="wp-block-paragraph">Well, a dictionary comprehension is a quick and concise way to <a href="https://blog.finxter.com/how-to-create-a-dictionary-from-two-numpy-arrays/" title="How to Create a Dictionary From Two NumPy Arrays?" target="_blank" rel="noreferrer noopener">create a dictionary </a>into a new one by applying a transforming operation for each of its members if needed. As you may have noticed here we are focused on dictionary comprehension, however, if you are interested in list comprehension I suggest you read this great <a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener">article</a> also in Finxter.</p>



<p class="wp-block-paragraph">The syntax is:</p>



<p class="wp-block-paragraph">Dictionary comprehension</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="">{ expression + context }</pre>



<p class="wp-block-paragraph">Example:</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 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
pow3_my_dict = {k:v**3 for (k,v) in my_dict.items()} 
# {'a': 1, 'c': 27, 'b': 8, 'd': 64}
</pre>



<p class="wp-block-paragraph">Explanation:</p>



<ul class="wp-block-list"><li><strong>Expression</strong>: <code>k:v**3</code> ? it tells python what to do with the values of the dictionary. In this case, we are applying the third power. This is 1<sup>^3</sup>, 2<sup>^3</sup>, 3<sup>^3</sup>, 4<sup>^3</sup></li></ul>



<ul class="wp-block-list"><li><strong>Context</strong>: <code>for (k,v) in my_dict.items()</code> ? it tells which items of the dictionary are going to be transformed. In this case, all of them. The context is an arbitrary number of for and if.</li></ul>



<p class="wp-block-paragraph">Example with an IF 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="">pow3_my_dict = {k:v**3 for (k,v) in my_dict.items() if v &lt; 3} 
# {'a': 1, 'b': 8}</pre>



<p class="wp-block-paragraph">As you can see, it creates a new dictionary with the values where the IF statement is true.</p>



<p class="wp-block-paragraph">Having said that, you could ask yourself: <em><strong>“Could I create a dictionary using the dictionary comprehension without having a previous dictionary?”</strong></em> Although this is a little far away from the subject we are focused, the answer is <strong><em>yes</em></strong>. We could create a new dictionary where the context is an iterable but not necessarily a dictionary. We could use the function range to generate the iterables or even using a given <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener">list</a>. Let us see some examples:</p>



<p class="wp-block-paragraph"><strong>Range function:</strong></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="">{num: num*num for num in range(1, 4)} 
# {1: 1, 2: 4, 3: 9}</pre>



<p class="wp-block-paragraph"><strong>List:</strong></p>



<p class="wp-block-paragraph">Imagine you have a list of customers that some have been introduced into the system with uppercase, lowercase or capitalized. And your job is to transform them into a dictionary in lowercase and pass the results to the system again. This could be a valid solution:</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="">customer_list = ['Andrew@test.com', 'RITA@hooli.com', 'anne@TROAT.COM']
print({x.lower() : 1 for x in customer_list})
# {'rita@hooli.com': 1, 'anne@troat.com': 1, 'andrew@test.com': 1}
</pre>



<p class="wp-block-paragraph">So, coming back from this parenthesis, the solution to reverse a dictionary using dictionary comprehension would be:</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 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
{v: k for k,v in my_dict.items()} 
# {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
</pre>



<p class="wp-block-paragraph">Explanation:</p>



<p class="wp-block-paragraph">The transformation here is to change the order the <code>key:value</code> pairs to have a <code>value:key</code> pairs. So, what we tell Python is: “Apply this transformation <code>v,k</code> (change the order) for every item <code>(k,v)</code> in the dictionary given”.</p>



<ul class="wp-block-list"><li>Expression: <code>v:k</code></li><li>Context: <code>for k,v in my_dict.items() </code></li></ul>



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



<p class="wp-block-paragraph">In this article we have learnt how to reverse the <code>key:value</code> pairs of a dictionary using:</p>



<ul class="wp-block-list"><li>The structure <code>for</code> loop</li><li>The <code>zip</code> function</li><li>The <code>map()</code> and <code>reversed()</code> function, how to combine them and what is an iterable.</li><li>The dictionary comprehension, and the parts represented in it by the expression and the context</li></ul>



<p class="wp-block-paragraph">To explain this we have explored what a dictionary is. What their properties are such as the immutability and the uniqueness of the key. We also have covered what happens if we repeat a key with a different value or by the contrary we use a number twice as a key although one was a float type and the other was an integer type.</p>



<p class="wp-block-paragraph">Finally, we have discovered that dictionary comprehension is becoming more popular than functions like <code>map()</code> because, if you do not abuse, it helps you to shorten the number of lines of your code making it more clean, easy to understand, elegant and more Pythonic. In case you want to get deeper in this matter please read this great <a href="https://blog.finxter.com/python-dictionary-comprehension/" target="_blank" rel="noreferrer noopener">article</a> about dictionary comprehension.</p>



<p>The post <a href="https://blog.finxter.com/how-to-switch-keys-and-values-in-a-python-dictionary/">How to Switch Keys and Values in a Python Dictionary?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</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-08-15 09:42:29 by W3 Total Cache
-->