Sick Gaming
[Tut] Python dict() — A Simple Guide with Video - 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 dict() — A Simple Guide with Video (/thread-99024.html)



[Tut] Python dict() — A Simple Guide with Video - xSicKxBot - 03-20-2022

Python dict() — A Simple Guide with Video

<div><p class="has-pale-cyan-blue-background-color has-background">Python’s built-in <code>dict()</code> function creates and returns a new dictionary object from the comma-separated argument list of <code>key = value</code> mappings. For example, <code>dict(name = 'Alice', age = 22, profession = 'programmer')</code> creates a dictionary with three mappings: <code>{'name': 'Alice', 'age': 22, 'profession': 'programmer'}</code>. A dictionary is an unordered and mutable data structure, so it can be changed after creation.</p>
<p>Read more about dictionaries in our full tutorial about <a href="https://blog.finxter.com/python-dictionary/" target="_blank" rel="noreferrer noopener" title="Python Dictionary – The Ultimate Guide">Python Dictionaries</a>.</p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2020/12/dict-1024x576.jpg" alt="Python dict() Visual Explanation" class="wp-image-19909" srcset="https://blog.finxter.com/wp-content/uploads/2020/12/dict-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2020/12/dict-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2020/12/dict-768x432.jpg 768w, https://blog.finxter.com/wp-content/uploads/2020/12/dict-150x84.jpg 150w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<h2>Usage</h2>
<p>Learn by example! Here are some examples of how to use the <code>dict()</code> <a href="https://blog.finxter.com/python-built-in-functions/" title="Python Built-In Functions">built-in 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="">>>> dict(name = 'Alice')
{'name': 'Alice'}
>>> dict(name = 'Alice', age = 22)
{'name': 'Alice', 'age': 22}
>>> dict(name = 'Alice', age = 22, profession = 'programmer')
{'name': 'Alice', 'age': 22, 'profession': 'programmer'}</pre>
<p>You can pass an arbitrary number of those comma-separated <code>key = value</code> pairs into the <code>dict()</code> constructor. </p>
<h2>Video dict()</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">
<div class="ast-oembed-container"><iframe loading="lazy" title="Python dict() — A Simple Guide" width="1400" height="788" src="https://www.youtube.com/embed/Y3oVGAOdr8M?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<h2>Syntax dict()</h2>
<p>You can use the <code>dict()</code> method with an arbitrary number of <code>key=value</code> arguments, comma-separated. </p>
<pre class="wp-block-preformatted"><strong>Syntax: </strong>There are four ways of using the constructor:
<code>dict() -&gt; new empty dictionary dict(mapping) -&gt; new dictionary initialized from a mapping object's (key, value) pairs
dict(iterable) -&gt; new dictionary initialized from an iterable of (key, value) tuples
dict(**kwargs) -&gt; new dictionary initialized with the name=value pairs in the keyword argument list.</code></pre>
</p>
<h2>Interactive Shell Exercise: Understanding dict()</h2>
<p>Consider the following interactive code:</p>
<p> <iframe loading="lazy" src="https://trinket.io/embed/python/3b90f6252a" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="356" frameborder="0"></iframe> </p>
<p><em><strong>Exercise</strong>: </em>Guess the output before running the code. </p>
<hr class="wp-block-separator"/>
<p><strong>But before we move on, I’m excited to present you my brand-new Python book <a rel="noreferrer noopener" href="https://amzn.to/2WAYeJE" target="_blank" title="https://amzn.to/2WAYeJE">Python One-Liners</a></strong> (Amazon Link).</p>
<p>If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a <strong>single line of Python code.</strong> But it’s also an <strong>introduction to computer science</strong>, data science, machine learning, and algorithms. <strong><em>The universe in a single line of Python!</em></strong></p>
<div class="wp-block-image">
<figure class="aligncenter"><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noopener noreferrer"><img loading="lazy" width="215" height="283" src="https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png" alt="" class="wp-image-5969"/></a></figure>
</div>
<p>The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). </p>
<p>Link: <a href="https://nostarch.com/pythononeliners" target="_blank" rel="noreferrer noopener">https://nostarch.com/pythononeliners</a></p>
<hr class="wp-block-separator"/>
<p>The <code>dict()</code> function has many different options to be called with different types of arguments. You’ll learn different ways to use the <code>dict()</code> function next. </p>
<h2>How to Create an Empty Dictionary?</h2>
<p>You can create an empty dictionary by using Python’s built-in <code>dict()</code> function without any argument. This returns an empty dictionary. As the dictionary is a mutable data structure, you can add more mappings later by using the <code>d[key] = value</code> 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="">>>> d = dict()
>>> d['Alice'] = 22
>>> d
{'Alice': 22}</pre>
<h2>How to Create a Dictionary Using Only Keyword Arguments?</h2>
<p>You can create a dictionary with initial <code>key: value</code> mappings by using a list of comma-separated arguments such as in <code>dict(name = 'Alice', age = 22)</code> to create the dictionary <code>{'name': 'Alice', 'age': 22}</code>. These are called <strong><em><a href="https://blog.finxter.com/python-double-asterisk/" target="_blank" rel="noreferrer noopener" title="Python Double Asterisk (**)">keyword arguments</a></em></strong> because each argument value has its associated 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="">>>> dict(name = 'Alice', age = 22)
{'name': 'Alice', 'age': 22}</pre>
<h2>How to Create a Dictionary Using an Iterable?</h2>
<p>You can initialize your new dictionary by using an iterable as an input for the <code>dict(iterable)</code> function. Python expects that the iterable contains <code>(key, value)</code> pairs. An example iterable is a list of tuples or a list of lists. The first values of the inner collection types are the keys and the second values of the inner collection types are the values of the new dictionary. </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([(1, 'one'), (2, 'two')])
{1: 'one', 2: 'two'}
>>> dict([[1, 'one'], [2, 'two']])
{1: 'one', 2: 'two'}
>>> dict(((1, 'one'), (2, 'two')))
{1: 'one', 2: 'two'}</pre>
<p>Note that you can use inner tuples, inner lists, outer tuples or outer lists—as long as each inner collection contains exactly two values. If it contains more, Python raises an <code>ValueError: dictionary update sequence element</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="">>>> dict([(1, 'one', 1.0), (2, 'two', 2.0)])
Traceback (most recent call last): File "&lt;pyshell#22>", line 1, in &lt;module> dict([(1, 'one', 1.0), (2, 'two', 2.0)])
ValueError: dictionary update sequence element #0 has length 3; 2 is required</pre>
<p>You can fix this <code>ValueError</code> by passing only two values in the inner collections. For example use a list of tuples with only two but not three tuple elements. </p>
<h2>How to Create a Dictionary Using an Existing Mapping Object?</h2>
<p>If you already have a mapping object such as a dictionary mapping keys to values, you can pass this object as an argument into the <code>dict()</code> function. Python will then create a new dictionary based on the existing <code>key: value</code> mappings in the argument. The resulting dictionary will be a new object so if you change it, the changes are not reflected in the original mapping object. </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 = {'Alice': 22, 'Bob': 23, 'Carl': 55}
>>> d2 = dict(d)
>>> d
{'Alice': 22, 'Bob': 23, 'Carl': 55}</pre>
<p>If you now change the original dictionary, the change is not reflected in the new dictionary <code>d2</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="">>>> d['David'] = 66
>>> d
{'Alice': 22, 'Bob': 23, 'Carl': 55, 'David': 66}
>>> d2
{'Alice': 22, 'Bob': 23, 'Carl': 55}</pre>
<h2>How to Create a Dictionary Using a Mapping Object and Keyword Arguments?</h2>
<p>Interestingly, you can also pass a mapping object into the <code>dict()</code> function and add some more <code>key: value</code> mappings using keyword arguments after the first mapping argument. For example, <code>dict({'Alice': 22}, Bob = 23)</code> creates a new dictionary with both <code>key:value</code> mappings <code>{'Alice': 22, 'Bob': 23}</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="">>>> dict({'Alice': 22}, Bob = 23)
{'Alice': 22, 'Bob': 23}
>>> dict({'Alice': 22}, Bob = 23, Carl = 55)
{'Alice': 22, 'Bob': 23, 'Carl': 55}</pre>
<h2>How to Create a Dictionary Using an Iterable and Keyword Arguments?</h2>
<p>Similarly, you can also pass an iterable of (key, value) tuples into the <code>dict()</code> function and add some more <code>key: value</code> mappings using keyword arguments after the first mapping argument. For example, <code>dict([('Alice', 22)], Bob = 23)</code> creates a new dictionary with both <code>key:value</code> mappings <code>{'Alice': 22, 'Bob': 23}</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="">>>> dict([('Alice', 22)], Bob = 23)
{'Alice': 22, 'Bob': 23}
>>> dict([('Alice', 22), ('Carl', 55)], Bob = 23)
{'Alice': 22, 'Carl': 55, 'Bob': 23}</pre>
<h2>Summary</h2>
<p>Python’s built-in <code>dict()</code> function creates and returns a new dictionary object from the comma-separated argument list of <code>key = value</code> mappings. </p>
<p>For example, <code>dict(name = 'Alice', age = 22, profession = 'programmer')</code> creates a dictionary with three mappings: <code>{'name': 'Alice', 'age': 22, 'profession': 'programmer'}</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="">>>> dict(name = 'Alice', age = 22, profession = 'programmer')
{'name': 'Alice', 'age': 22, 'profession': 'programmer'}</pre>
<p>A dictionary is an unordered and mutable data structure, so it can be changed after creation.</p>
<p>I hope you enjoyed the article! To improve your Python education, you may want to join the popular free <a href="https://blog.finxter.com/email-academy/" target="_blank" rel="noreferrer noopener" title="Email Academy">Finxter Email Academy</a>:</p>
<hr class="wp-block-separator"/>
<p>Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!</p>
<h2>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>
</p>
<p>The post <a href="https://blog.finxter.com/python-dict/">Python dict() — A Simple Guide with Video</a> first appeared on <a href="https://blog.finxter.com">Finxter</a>. </p>
</div>


https://www.sickgaming.net/blog/2020/12/31/python-dict-a-simple-guide-with-video/