{"id":122692,"date":"2020-12-31T11:15:45","date_gmt":"2020-12-31T11:15:45","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=19866"},"modified":"2020-12-31T11:15:45","modified_gmt":"2020-12-31T11:15:45","slug":"python-dict-a-simple-guide-with-video","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/12\/31\/python-dict-a-simple-guide-with-video\/","title":{"rendered":"Python dict() \u2014 A Simple Guide with Video"},"content":{"rendered":"<p class=\"has-pale-cyan-blue-background-color has-background\">Python&#8217;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>\n<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 \u2013 The Ultimate Guide\">Python Dictionaries<\/a>.<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" 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=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<h2>Usage<\/h2>\n<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>\n<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')\n{'name': 'Alice'}\n>>> dict(name = 'Alice', age = 22)\n{'name': 'Alice', 'age': 22}\n>>> dict(name = 'Alice', age = 22, profession = 'programmer')\n{'name': 'Alice', 'age': 22, 'profession': 'programmer'}<\/pre>\n<p>You can pass an arbitrary number of those comma-separated <code>key = value<\/code> pairs into the <code>dict()<\/code> constructor. <\/p>\n<h2>Video dict()<\/h2>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"Python dict() \u2014 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>\n<\/div>\n<\/figure>\n<h2>Syntax dict()<\/h2>\n<p>You can use the <code>dict()<\/code> method with an arbitrary number of <code>key=value<\/code> arguments, comma-separated. <\/p>\n<pre class=\"wp-block-preformatted\"><strong>Syntax: <\/strong>There are four ways of using the constructor:\n<code>dict() -&gt; new empty dictionary dict(mapping) -&gt; new dictionary initialized from a mapping object's (key, value) pairs\ndict(iterable) -&gt; new dictionary initialized from an iterable of (key, value) tuples\ndict(**kwargs) -&gt; new dictionary initialized with the name=value pairs in the keyword argument list.<\/code><\/pre>\n<\/p>\n<h2>Interactive Shell Exercise: Understanding dict()<\/h2>\n<p>Consider the following interactive code:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/3b90f6252a\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen=\"\" width=\"100%\" height=\"356\" frameborder=\"0\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: <\/em>Guess the output before running the code. <\/p>\n<hr class=\"wp-block-separator\"\/>\n<p><strong>But before we move on, I&#8217;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>\n<p>If you like one-liners, you&#8217;ll LOVE the book. It&#8217;ll teach you everything there is to know about a <strong>single line of Python code.<\/strong> But it&#8217;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>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noopener noreferrer\"><img decoding=\"async\" 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>\n<\/div>\n<p>The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). <\/p>\n<p>Link: <a href=\"https:\/\/nostarch.com\/pythononeliners\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/nostarch.com\/pythononeliners<\/a><\/p>\n<hr class=\"wp-block-separator\"\/>\n<p>The <code>dict()<\/code> function has many different options to be called with different types of arguments. You&#8217;ll learn different ways to use the <code>dict()<\/code> function next. <\/p>\n<h2>How to Create an Empty Dictionary?<\/h2>\n<p>You can create an empty dictionary by using Python&#8217;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>\n<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()\n>>> d['Alice'] = 22\n>>> d\n{'Alice': 22}<\/pre>\n<h2>How to Create a Dictionary Using Only Keyword Arguments?<\/h2>\n<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>\n<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)\n{'name': 'Alice', 'age': 22}<\/pre>\n<h2>How to Create a Dictionary Using an Iterable?<\/h2>\n<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>\n<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')])\n{1: 'one', 2: 'two'}\n>>> dict([[1, 'one'], [2, 'two']])\n{1: 'one', 2: 'two'}\n>>> dict(((1, 'one'), (2, 'two')))\n{1: 'one', 2: 'two'}<\/pre>\n<p>Note that you can use inner tuples, inner lists, outer tuples or outer lists&#8212;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>\n<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)])\nTraceback (most recent call last): File \"&lt;pyshell#22>\", line 1, in &lt;module> dict([(1, 'one', 1.0), (2, 'two', 2.0)])\nValueError: dictionary update sequence element #0 has length 3; 2 is required<\/pre>\n<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>\n<h2>How to Create a Dictionary Using an Existing Mapping Object?<\/h2>\n<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>\n<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}\n>>> d2 = dict(d)\n>>> d\n{'Alice': 22, 'Bob': 23, 'Carl': 55}<\/pre>\n<p>If you now change the original dictionary, the change is not reflected in the new dictionary <code>d2<\/code>. <\/p>\n<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\n>>> d\n{'Alice': 22, 'Bob': 23, 'Carl': 55, 'David': 66}\n>>> d2\n{'Alice': 22, 'Bob': 23, 'Carl': 55}<\/pre>\n<h2>How to Create a Dictionary Using a Mapping Object and Keyword Arguments?<\/h2>\n<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>\n<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)\n{'Alice': 22, 'Bob': 23}\n>>> dict({'Alice': 22}, Bob = 23, Carl = 55)\n{'Alice': 22, 'Bob': 23, 'Carl': 55}<\/pre>\n<h2>How to Create a Dictionary Using an Iterable and Keyword Arguments?<\/h2>\n<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>\n<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)\n{'Alice': 22, 'Bob': 23}\n>>> dict([('Alice', 22), ('Carl', 55)], Bob = 23)\n{'Alice': 22, 'Carl': 55, 'Bob': 23}<\/pre>\n<h2>Summary<\/h2>\n<p>Python&#8217;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>\n<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>\n<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')\n{'name': 'Alice', 'age': 22, 'profession': 'programmer'}<\/pre>\n<p>A dictionary is an unordered and mutable data structure, so it can be changed after creation.<\/p>\n<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>\n<hr class=\"wp-block-separator\"\/>\n<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>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<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>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n<\/p>\n<\/p>\n<p>The post <a href=\"https:\/\/blog.finxter.com\/python-dict\/\">Python dict() \u2014 A Simple Guide with Video<\/a> first appeared on <a href=\"https:\/\/blog.finxter.com\">Finxter<\/a>. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python&#8217;s built-in dict() function creates and returns a new dictionary object from the comma-separated argument list of key = value mappings. For example, dict(name = &#8216;Alice&#8217;, age = 22, profession = &#8216;programmer&#8217;) creates a dictionary with three mappings: {&#8216;name&#8217;: &#8216;Alice&#8217;, &#8216;age&#8217;: 22, &#8216;profession&#8217;: &#8216;programmer&#8217;}. A dictionary is an unordered and mutable data structure, so it [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-122692","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/122692","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=122692"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/122692\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=122692"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=122692"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=122692"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}