{"id":3488,"date":"2026-11-26T11:49:25","date_gmt":"2026-11-26T11:49:25","guid":{"rendered":"https:\/\/gyanipandit.com\/programming\/?p=3488"},"modified":"2026-11-26T11:49:38","modified_gmt":"2026-11-26T11:49:38","slug":"python-dictionary-setdefault","status":"publish","type":"post","link":"https:\/\/gyanipandit.com\/programming\/python-dictionary-setdefault\/","title":{"rendered":"Python Dictionary setdefault() Method with Examples"},"content":{"rendered":"<p>The <code>setdefault()<\/code> method does two jobs in one call. If the key <strong>exists<\/strong>, it simply returns its value. If the key is <strong>missing<\/strong>, it adds the key with a default value and returns that default. It is especially useful for grouping data into lists. This page explains it with outputs and compares it with <code>get()<\/code> and <code>defaultdict<\/code>.<\/p>\n<h2>Syntax<\/h2>\n<pre class=\"wp-block-code\"><code>dictionary.setdefault(key, default=None)<\/code><\/pre>\n<ul>\n<li><code>key<\/code>: the key to look up.<\/li>\n<li><code>default<\/code>: the value to insert if the key is missing. If you leave it out, <code>None<\/code> is inserted.<\/li>\n<li>Returns the value of the key (existing or newly inserted).<\/li>\n<\/ul>\n<h2>Example 1: Key Is Missing<\/h2>\n<pre class=\"wp-block-code\"><code>stock = {'pen': 10, 'pencil': 25}\n\nprint(stock.setdefault('eraser', 5))\nprint(stock)<\/code><\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>5\n{'pen': 10, 'pencil': 25, 'eraser': 5}<\/code><\/pre>\n<p><code>'eraser'<\/code> was not in the dictionary, so it was added with the value 5, and 5 was returned.<\/p>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" src=\"https:\/\/gyanipandit.com\/programming\/wp-content\/uploads\/2022\/10\/THE-setdefault-METHOD.jpg\" alt=\"Python dictionary setdefault example\" \/><\/figure>\n<h2>Example 2: Key Already Exists<\/h2>\n<pre class=\"wp-block-code\"><code>print(stock.setdefault('pen', 99))\nprint(stock)<\/code><\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>10\n{'pen': 10, 'pencil': 25, 'eraser': 5}<\/code><\/pre>\n<p>The existing value 10 is returned. The default 99 is ignored, and nothing changes.<\/p>\n<h2>Example 3: No Default Given<\/h2>\n<pre class=\"wp-block-code\"><code>print(stock.setdefault('ruler'))\nprint(stock)<\/code><\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>None\n{'pen': 10, 'pencil': 25, 'eraser': 5, 'ruler': None}<\/code><\/pre>\n<h2>Where setdefault() Really Shines: Grouping<\/h2>\n<p>Suppose you want to group words by their first letter. Without <code>setdefault()<\/code> you would need an <code>if<\/code> check for every word. With it, one line does the job:<\/p>\n<pre class=\"wp-block-code\"><code>words = ['apple', 'avocado', 'banana', 'blueberry', 'cherry']\ngroups = {}\n\nfor w in words:\n    groups.setdefault(w[0], []).append(w)\n\nprint(groups)<\/code><\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}<\/code><\/pre>\n<p>For each word, <code>setdefault()<\/code> returns the existing list for that letter, or creates an empty one first. Then <code>append()<\/code> adds the word to it.<\/p>\n<h2>setdefault() vs get() vs defaultdict<\/h2>\n<table>\n<thead>\n<tr>\n<th><\/th>\n<th><code>get(key, default)<\/code><\/th>\n<th><code>setdefault(key, default)<\/code><\/th>\n<th><code>defaultdict<\/code><\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Missing key<\/td>\n<td>Returns default, does <strong>not<\/strong> add it<\/td>\n<td>Adds the key with default and returns it<\/td>\n<td>Adds the key automatically on first access<\/td>\n<\/tr>\n<tr>\n<td>Changes the dictionary?<\/td>\n<td>Never<\/td>\n<td>Only if the key is missing<\/td>\n<td>Yes, on access<\/td>\n<\/tr>\n<tr>\n<td>Best for<\/td>\n<td>Reading safely<\/td>\n<td>Occasional &#8220;add if missing&#8221;<\/td>\n<td>Lots of grouping or counting<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<pre class=\"wp-block-code\"><code>s = {'pen': 10}\nprint(s.get('ink', 0), s)          # 0 {'pen': 10}  (no change)\n\nfrom collections import defaultdict\ng = defaultdict(list)\nfor w in words:\n    g[w[0]].append(w)\nprint(dict(g))<\/code><\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>0 {'pen': 10}\n{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}<\/code><\/pre>\n<h2>One Thing to Watch<\/h2>\n<p>The default value is created every time you call <code>setdefault()<\/code>, even when the key already exists. In <code>d.setdefault(k, [])<\/code> that is just a cheap empty list, but avoid passing something expensive, like a function call that does heavy work, as the default.<\/p>\n<h2>Frequently Asked Questions<\/h2>\n<h3>What does setdefault() return?<\/h3>\n<p>The value of the key: the existing one if the key is present, or the default it just inserted.<\/p>\n<h3>What is the difference between get() and setdefault()?<\/h3>\n<p>Both return a default for a missing key, but only <code>setdefault()<\/code> also adds that key to the dictionary.<\/p>\n<h3>Does setdefault() overwrite an existing value?<\/h3>\n<p>No. If the key exists, its value is left unchanged.<\/p>\n<p>Related: <a href=\"https:\/\/gyanipandit.com\/programming\/python-dictionary-fromkeys\/\">Python dictionary fromkeys()<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The setdefault() method does two jobs in one call. If the key exists, it simply returns its value. If the key is missing, it adds the key with a default value and returns that default. It is especially useful for grouping data into lists. This page explains it with outputs and compares it with get() &#8230; <a title=\"Python Dictionary setdefault() Method with Examples\" class=\"read-more\" href=\"https:\/\/gyanipandit.com\/programming\/python-dictionary-setdefault\/\" aria-label=\"Read more about Python Dictionary setdefault() Method with Examples\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[25],"tags":[26,27],"class_list":["post-3488","post","type-post","status-publish","format-standard","hentry","category-python-tutorial","tag-python","tag-python-tutorial"],"_links":{"self":[{"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/posts\/3488","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/comments?post=3488"}],"version-history":[{"count":3,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/posts\/3488\/revisions"}],"predecessor-version":[{"id":6161,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/posts\/3488\/revisions\/6161"}],"wp:attachment":[{"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/media?parent=3488"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/categories?post=3488"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/tags?post=3488"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}