Sick Gaming
[Tut] Python One Line Dictionary - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: Python (https://www.sickgaming.net/forum-83.html)
+--- Thread: [Tut] Python One Line Dictionary (/thread-97361.html)



[Tut] Python One Line Dictionary - xSicKxBot - 09-21-2020

Python One Line Dictionary

<div><p>Python’s dictionary data structure is one of the most powerful, most underutilized data structures in Python. Why? Because checking membership is more efficient for dictionaries than for lists, while accessing elements is easier for dictionaries than for sets.</p>
<p>In this tutorial, you’ll learn how to perform four common dictionary operations in <a href="https://blog.finxter.com/python-one-line-x/" title="Python One Line X" target="_blank" rel="noreferrer noopener">one line of Python code</a>. By studying these problems, you’ll not only learn how to use dictionaries in Python, but you’ll become a better coder overall. So, let’s dive into the first problem: creating a dictionary from a list in one line.</p>
<h2>Python Create Dictionary From List in One Line</h2>
<p><strong>Challenge</strong>: Create a dictionary from a <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">list </a>in one line of Python.</p>
<p><strong>Example</strong>: Say, you want to have the list indices as keys and the list elements as 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=""># Given a list:
a = ['Alice', 'Liz', 'Bob'] # One-Line Statement Creating a Dict:
d = one-line-statement print(d)
# {0: 'Alice', 1: 'Liz', 2: 'Bob'}
</pre>
<p><strong>Solution</strong>: There are multiple ways to accomplish this task. Let’s learn the most Pythonic one next:</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=""># Given a list:
a = ['Alice', 'Liz', 'Bob'] # One-Line Statement Creating a Dict:
d = dict(enumerate(a)) print(d)
# {0: 'Alice', 1: 'Liz', 2: 'Bob'}</pre>
<p>The one-liner <code>dict(enumerate(a))</code> first creates an iterable of <code>(index, element)</code> tuples from the list <code>a</code> using the <a href="https://blog.finxter.com/the-top-18-best-python-tricks/" title="Top 18 Cool Python Tricks" target="_blank" rel="noreferrer noopener"><code>enumerate</code> </a>function. The <code>dict()</code> <a href="https://blog.finxter.com/python-init/" title="What is __init__ in Python?" target="_blank" rel="noreferrer noopener">constructor </a>than transforms this iterable of tuples to <code>(key, value)</code> mappings. The <code>index</code> <a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" title="The Ultimate Guide To Python Tuples">tuple </a>value becomes the new <code>key</code>. The <code>element</code> tuple value becomes the new <code>value</code>. </p>
<p>Try it yourself in our interactive code shell:</p>
<p> <iframe src="https://trinket.io/embed/python/273d008079" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Explore the <code>enumerate()</code> function further by printing its output!</em></p>
<h2>Python One Line For Loop to Create Dictionary</h2>
<p><strong>Challenge</strong>: How to create a dictionary from all elements in a list using a <a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" title="Python One Line For Loop [A Simple Tutorial]" target="_blank" rel="noreferrer noopener">single-line for loop</a>?</p>
<p><strong>Example</strong>: Say, you want to replace the following four-liner code snippet with a <a href="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener" title="https://pythononeliners.com/">Python one-liner</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="">a = ['Alice', 'Liz', 'Bob'] data = {}
for item in a: data[item] = item</pre>
<p>How do you accomplish this?</p>
<p><strong>Solution</strong>: Use <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> to replace the <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]"><code>for</code> loop</a> construct with a single line of 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="">a = ['Alice', 'Liz', 'Bob'] # One-Liner Dictionary For Loop
data = {item:item for item in a} print(data)
# {'Alice': 'Alice', 'Liz': 'Liz', 'Bob': 'Bob'}</pre>
<p><strong>Dictionary Comprehension</strong> is a concise and memory-efficient way to <strong><a href="https://blog.finxter.com/python-dictionary-comprehension/" title="Python Dictionary Comprehension: A Powerful One-Liner Tutorial">create </a>and initialize dictionaries</strong> in one line of Python code. It consists of two parts: expression and context. The <strong>expression </strong>defines how to map keys to values. The <strong>context </strong>loops over an iterable using a single-line for loop and defines which (key,value) pairs to include in the new dictionary.</p>
<p>You can learn about dictionary comprehension in my full video tutorial:</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">
<div class="ast-oembed-container"><iframe title="Python Dictionary Comprehension - A Powerful One-Liner Tutorial" width="1400" height="788" src="https://www.youtube.com/embed/TlEC5Jx72Uc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><strong>Related Article</strong>: <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 — Complete Guide</a></p>
<h2>Python Print Dictionary One Line</h2>
<p><strong>Challenge</strong>: How can you <a href="https://blog.finxter.com/print-python-list/" target="_blank" rel="noreferrer noopener" title="Print a Python List Beautifully [Click &amp; Run Code]">print </a>a dictionary in a well-structured way using only a single line of Python code (without using <a href="https://blog.finxter.com/how-to-write-multiple-statements-on-a-single-line-in-python/" target="_blank" rel="noreferrer noopener" title="How to Write Multiple Statements on a Single Line in Python?">multiple lines</a> to create the output)?</p>
<p><strong>Solution</strong>: Use the pretty print function!</p>
<p>The built-in module <code>pprint</code> contains the function <code>pprint</code>. This will ‘pretty print’ 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">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><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]">Printing </a>the dictionary this way, doesn’t change the dictionary in any way but makes it more readable on the Python shell!</p>
<h2>Iterate Over Dictionary Python One Line</h2>
<p><strong>Challenge</strong>: How to <a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops">iterate </a>over a dictionary in Python in one line?</p>
<p><strong>Example</strong>: Say, you want to go over each <code>(key, value)</code> pair of a dictionary like 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="">age = {'Alice': 19, 'Bob': 23, 'Frank': 53} # Iterate over dictionary (key, value) pairs
for name in age: key, value = name, age[name] print(key, value) '''
OUTPUT:
Alice 19
Bob 23
Frank 53 '''</pre>
<p>But you want to do it in a <a href="https://blog.finxter.com/how-to-execute-multiple-lines-in-a-single-line-python-from-command-line/" target="_blank" rel="noreferrer noopener" title="How to Execute Multiple Lines in a Single Line Python From Command-Line?">single line</a> of Python code! How?</p>
<p><strong>Solution</strong>: Use the <code>dict.items()</code> method to obtain the iterable. Then, use a <a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" title="Python One Line For Loop [A Simple Tutorial]" target="_blank" rel="noreferrer noopener">single-line for loop</a> to iterate over it. </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="">age = {'Alice': 19, 'Bob': 23, 'Frank': 53} # Iterate over dictionary (key, value) pairs
for k,v in age.items(): print(k,v) '''
OUTPUT:
Alice 19
Bob 23
Frank 53 '''
</pre>
<p>The output is the same while the code is much more concise. The <code>items()</code> method of a dictionary object creates an iterable of <code>(key, value)</code> tuple pairs from the dictionary.</p>
<h2>Python Update Dictionary in One Line</h2>
<p><strong>Challenge</strong>: Given a dictionary and a <code>(key, value)</code> pair. The <code>key</code> may or may not already exist in the dictionary. How to update the dictionary in one line of Python? </p>
<p><strong>Solution</strong>: Use the square bracket notation <code>dict[key] = value</code> to create a new mapping from <code>key</code> to <code>value</code> in the dictionary. There are two cases:</p>
<ul>
<li>The <code>key</code> already existed before and was associated to the old <code>value_old</code>. In this case, the new <code>value</code> overwrites the old <code>value_old</code> after updating the dictionary.</li>
<li>The <code>key</code> didn’t exist before in the dictionary. In this case, it is created for the first time and associated to <code>value</code>.</li>
</ul>
<p>Here’s the 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="">age = {'Alice': 19, 'Bob': 23, 'Frank': 53} print(f"Alice is {age['Alice']} years old")
# Alice is 19 years old # Alice's Birthday
age['Alice'] = 20 print(f"Alice is {age['Alice']} years old")
# Alice is 20 years old</pre>
<p><strong>Challenge 2</strong>: But what if you want to update only if the key didn’t exist before. In other words, you don’t want to overwrite an existing mapping?</p>
<p><strong>Solution</strong>: In this case, you can use the check if key in dict to differentiate the two cases:</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="">age = {'Alice': 19, 'Bob': 23, 'Frank': 53} print(f"Alice is {age['Alice']} years old")
# Alice is 19 years old # Alice's Birthday
if 'Alice' not in age: age['Alice'] = 20 print(f"Alice is {age['Alice']} years old")
# Alice is 19 years old</pre>
<p>Now, you may want to write this in a single line of code. You can do it the naive way:</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 'Alice' not in age: age['Alice'] = 20</pre>
<p>An better alternative is the <a href="https://docs.python.org/3/library/stdtypes.html#dict.setdefault" target="_blank" rel="noreferrer noopener" title="https://docs.python.org/3/library/stdtypes.html#dict.setdefault">dictionary.setdefault()</a> method:</p>
<p><code>setdefault(<em>key</em>[, <em>default</em>])</code> — If <em><code>key</code></em> is in the dictionary, return its value. If not, insert <em><code>key</code></em> with a value of <em><code>default</code></em> and return <em><code>default</code></em>. <em><code>default</code></em> defaults to <code>None</code>.</p>
<p>You can simply ignore the return value to update a key in a dictionary if it isn’t already present. </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="">age = {'Alice': 19, 'Bob': 23, 'Frank': 53} print(f"Alice is {age['Alice']} years old")
# Alice is 19 years old # Alice's Birthday
age.setdefault('Alice', 20) print(f"Alice is {age['Alice']} years old")
# Alice is 19 years old
</pre>
<p>The <code>age.setdefault('Alice', 20)</code> only inserts the key <code>'Alice'</code> if it isn’t already present (in which case it would associate the value 20 to it). But because it already exists, the command has no side effects and the new value does not overwrite the old one. </p>
<h2 class="wp-block-block">Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
<p>The post <a href="https://blog.finxter.com/python-one-line-dictionary/" target="_blank" rel="noopener noreferrer">Python One Line Dictionary</a> first appeared on <a href="https://blog.finxter.com/" target="_blank" rel="noopener noreferrer">Finxter</a>.</p>
</div>


https://www.sickgaming.net/blog/2020/09/21/python-one-line-dictionary/