{"id":80197,"date":"2021-02-08T09:00:21","date_gmt":"2021-02-08T03:30:21","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=80197"},"modified":"2021-02-08T09:00:21","modified_gmt":"2021-02-08T03:30:21","slug":"python-defaultdict-module","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/","title":{"rendered":"Defaultdict Module in Python with Syntax and Examples"},"content":{"rendered":"<p>In this article, we\u2019ll learn about a very special and vividly used module in python, the defaultdict() module.<\/p>\n<p>Starting from basics, covering its syntax, parameters and advanced codes, we\u2019ll cover it all. So let\u2019s get started.<\/p>\n<h2>Defaultdict Module in Python<\/h2>\n<p>Dictionary in Python is an unordered collection of mutable lists. It is generally used for the purpose in which data has to be kept fixed, and no changes are required.<\/p>\n<p>The defaultdict module has the ability to hold and manipulate the codes better than any other module. It keeps a dictionary as its fixed elements always.<\/p>\n<p>A dictionary contains the immutable values, which can only be reciprocated in the code for any further alignment.<\/p>\n<p><strong>Example of Defaultdict Module in Python<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">thisistech = {1: 'wow', 2: 'welcome'}  \nprint(\"thisisdict: \")  \nprint(thisistech) \nprint(thisistech[1])\n\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">thisisdict:<br \/>\n{1: &#8216;wow&#8217;, 2: &#8216;welcome&#8217;}<br \/>\nwow<br \/>\n&gt;&gt;&gt;<\/div>\n<h3>More in Python DefaultDict<\/h3>\n<p>Python Defaultdict primarily contains two parts, one mutable and other immutable.<\/p>\n<p>If the mutable part is parsed it does not allow the immutable part to get executed and vice -versa.<\/p>\n<p><strong>Syntax: <\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">defaultdict(default_factory)\n\nImport defaultdict\nfrom collections import defaultdict\n# a coder can Create a defaultdict\n<\/pre>\n<p>Coders can create a defaultdict with the defaultdict() constructor in runtime.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">enternumber= defaultdict(i)\nchecknumber[a] = 1\nchecknumber[w] = 2\nprint(checknumber[c])\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\nerror<\/div>\n<h3>Parameters of defaultdict module in Python<\/h3>\n<p><strong>default_factory:<\/strong> This function acts as a factory as it stores multiple values in it at a particular runtime and also saves the same for future processing also.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from collections import defaultdict \ndef thisistech(): \n    return \"hello!user!\"\n\nd = defaultdict(thisistech) \nd[\"one\"] = 8\nd[\"two\"] = 9\n  \nprint(d[\"one\"]) \nprint(d[\"two\"]) \n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\n8<br \/>\n9<\/div>\n<h3>Inner Working of Python Defaultdict Module<\/h3>\n<p>Defaultdict adds parses values internally and displays the output.<\/p>\n<p><strong>Default_factory:<\/strong> It is a function returning the default value of the code to the user in such a way that it is mutable at any time.<\/p>\n<p><strong>Example of Python Defaultdict module:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from collections import defaultdict \np = defaultdict(lambda: \"thisistech\") \np[\"firstuser\"] = 1\np[\"seconduser\"] = 2 \nprint(p[\"firstuser\"]) \nprint(p[\"seconduser\"]) \nprint(p[\"firstuser\"]) \n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">1<br \/>\n2<br \/>\nwelcome<\/div>\n<p><strong>__missing__():<\/strong> This function takes default_factory as an argument in its main code, checks for the error and displays the error if any. It stops its execution in the meantime.<\/p>\n<p><strong>Example of Python _missing_():<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from collections import defaultdict        \np = defaultdict(lambda: \"thisistech\") \np[\"userone\"] = 300\np[\"usertwo\"] = 350\nprint(p.__missing__('userone')) \nprint(p.__missing__('usertwo')) \n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\nthisistech<br \/>\nthisistech<br \/>\n&gt;&gt;&gt;<\/div>\n<h4>Using List as default_factory<\/h4>\n<p>When a class list is passed in an empty dictionary it is parsed in such a way that a user finds it immutable and hence does not change its value.<\/p>\n<p><strong>Example of Using list as default_factory in Python:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from collections import defaultdict     \np = defaultdict(list)   \nfor number in range(3): \n    p[number].append(number)\n      \nprint(\"the appended list is:\") \nprint(p) \n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">the appended list is:<br \/>\ndefaultdict(&lt;class &#8216;list&#8217;&gt;, {0: [0], 1: [1], 2: [2]})<br \/>\n&gt;&gt;&gt;<\/div>\n<h4>Using int as default_factory<\/h4>\n<p>When the int class is parsed, it always interprets it line by line thus making it a mutable value.<\/p>\n<p><strong>Example of using int as Default_factory<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from collections import defaultdict\np= defaultdict(int) \n   \no= [1, 2, 3, 4, 2, 4, 1, 2] \n   \n\nfor usernumber in p: \n       \n   p[usernumber] += 1\n       \nprint(p) \n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">defaultdict(&lt;class &#8216;int&#8217;&gt;, {})<br \/>\n&gt;&gt;&gt;<\/div>\n<p><strong>Using \u2018int\u2019 as a Default Factory:<\/strong> Int(integer) can also be used in the default factory. And this can be simply done by giving the input statement as an integer and merging the same with list.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">n='thisistech'\nmydict=defaultdict(int)\nfor numbers in n:\n                mydict[i]+=1              \nmydict\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">error<\/div>\n<table style=\"height: 353px\" width=\"848\">\n<tbody>\n<tr>\n<td><b>Method or Attribute<\/b><\/td>\n<td><b>Description<\/b><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">.__copy__()<\/span><\/td>\n<td><span style=\"font-weight: 400\">Supports for copy.copy()<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">.default_factory<\/span><\/td>\n<td><span style=\"font-weight: 400\">Holds the callable object<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">.__missing__() t<\/span><\/td>\n<td><span style=\"font-weight: 400\">By default provides the missing value<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\"> .__getitem__()<\/span><\/td>\n<td><span style=\"font-weight: 400\">Called when can\u2019t find key in the data<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Parsing Animation tools of Defaultdict<\/h3>\n<h4>1. Counter<\/h4>\n<p>It is a built in data structure that is useful to count the occurrence of a number of values for a code.<\/p>\n<h4>2. Deque<\/h4>\n<p>Deque is a list used for inserting and removing items from the code. It acts as an interpreter which modifies the values as useful and not in the code.<\/p>\n<h4>3. ChainMap<\/h4>\n<p>ChainMap generally mixes dictionaries together and processes them in a way their values get combined and then returns a list of dictionaries. It does this without any restriction on the numeric value of dictionaries parsed.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this article, we saw what is Python defaultdict, how and when it is used, its attributes and parameters.<\/p>\n<p>A table has been summed up regarding what we\u2019ve discussed until now.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we\u2019ll learn about a very special and vividly used module in python, the defaultdict() module. Starting from basics, covering its syntax, parameters and advanced codes, we\u2019ll cover it all. So let\u2019s&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":80218,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[3356,3358,3359],"class_list":["post-80197","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-defaultdict-in-python","tag-defaultdict-module-in-python","tag-python-defaultdict"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Defaultdict Module in Python with Syntax and Examples - TechVidvan<\/title>\n<meta name=\"description\" content=\"Defaultdict is a sub-class of the dict class that returns a dictionary-like object. Learn defaultdict module in Python with syntax and example\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Defaultdict Module in Python with Syntax and Examples - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Defaultdict is a sub-class of the dict class that returns a dictionary-like object. Learn defaultdict module in Python with syntax and example\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-02-08T03:30:21+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-defaultdict-module.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Defaultdict Module in Python with Syntax and Examples - TechVidvan","description":"Defaultdict is a sub-class of the dict class that returns a dictionary-like object. Learn defaultdict module in Python with syntax and example","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/","og_locale":"en_US","og_type":"article","og_title":"Defaultdict Module in Python with Syntax and Examples - TechVidvan","og_description":"Defaultdict is a sub-class of the dict class that returns a dictionary-like object. Learn defaultdict module in Python with syntax and example","og_url":"https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-02-08T03:30:21+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-defaultdict-module.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Defaultdict Module in Python with Syntax and Examples","datePublished":"2021-02-08T03:30:21+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/"},"wordCount":609,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-defaultdict-module.jpg","keywords":["defaultdict in python","Defaultdict Module in Python","Python defaultdict"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/","url":"https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/","name":"Defaultdict Module in Python with Syntax and Examples - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-defaultdict-module.jpg","datePublished":"2021-02-08T03:30:21+00:00","description":"Defaultdict is a sub-class of the dict class that returns a dictionary-like object. Learn defaultdict module in Python with syntax and example","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-defaultdict-module.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-defaultdict-module.jpg","width":1200,"height":628,"caption":"Python defaultdict module"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/python-defaultdict-module\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Defaultdict Module in Python with Syntax and Examples"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/80197","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=80197"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/80197\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/80218"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=80197"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=80197"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=80197"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}