Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Container Types: A Quick Guide

#1
Python Container Types: A Quick Guide

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;1324280&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;starsonly&quot;:&quot;&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;title&quot;:&quot;Python Container Types: A Quick Guide&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</p></div>
<p>If you’re working with Python, most of the data structures you’ll think about are <strong><em>container types</em></strong>. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f682.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f683.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f683.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f683.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>These containers are <strong>special data structures that hold and manage collections of elements</strong>. Python’s most commonly used built-in container types include <a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" data-type="post" data-id="12043" target="_blank" rel="noreferrer noopener">tuples</a>, <a href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener">lists</a>, <a href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank" rel="noreferrer noopener">dictionaries</a>, <a href="https://blog.finxter.com/sets-in-python/" data-type="URL" data-id="https://blog.finxter.com/sets-in-python/" target="_blank" rel="noreferrer noopener">sets</a>, and <a href="https://blog.finxter.com/python-frozenset/" data-type="post" data-id="23301" target="_blank" rel="noreferrer noopener">frozensets</a> <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4e6.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />. These containers make it easy for you to store, manage and manipulate your data effectively and efficiently. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f603.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>You might be wondering what makes each container unique. Well, they all serve different purposes and have distinct characteristics. </p>
<ul>
<li>For instance, <strong>lists </strong>are <a href="https://blog.finxter.com/mutable-vs-immutable-objects-in-python/" data-type="post" data-id="204090" target="_blank" rel="noreferrer noopener">mutable</a> and ordered, allowing you to <a href="https://blog.finxter.com/add-elements-to-list-python/" data-type="post" data-id="9030" target="_blank" rel="noreferrer noopener">add</a>, <a href="https://blog.finxter.com/6-ways-to-remove-python-list-elements/" data-type="post" data-id="830190" target="_blank" rel="noreferrer noopener">remove</a>, or <a href="https://blog.finxter.com/how-to-replace-a-list-element-at-a-specific-index-in-python/" data-type="post" data-id="25378" target="_blank" rel="noreferrer noopener">modify</a> elements. </li>
<li><strong>Tuples</strong>, on the other hand, are immutable and ordered, which means once created, their elements cannot be changed <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2728.png" alt="✨" class="wp-smiley" style="height: 1em; max-height: 1em;" />. </li>
<li><strong>Dictionaries </strong>are mutable and store key-value pairs, making it efficient for data retrieval. </li>
<li>Lastly, sets and <strong>frozensets </strong>are unordered collections, with <strong>sets </strong>being mutable and frozensets <a href="https://blog.finxter.com/mutable-vs-immutable-objects-in-python/" data-type="post" data-id="204090" target="_blank" rel="noreferrer noopener">immutable</a>.</li>
</ul>
<p>As you explore Python, understanding these container types is essential, as they provide a foundation for organizing and manipulating your data.</p>
<h2 class="wp-block-heading">Basic Built-In Container Types</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="625" height="941" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-301.png" alt="" class="wp-image-1324379" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-301.png 625w, https://blog.finxter.com/wp-content/uplo...99x300.png 199w" sizes="(max-width: 625px) 100vw, 625px" /></figure>
</div>
<p>You might be wondering about Python’s built-in container types. Let’s dive into them and see how useful they can be! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f603.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3 class="wp-block-heading">List</h3>
<p class="has-global-color-8-background-color has-background">A List is a mutable sequence type in Python. It allows you to store a collection of objects in a defined order. With lists, you can add, remove or change items easily. </p>
<p>Example of <a href="https://blog.finxter.com/python-create-list-of-objects/" data-type="post" data-id="873019" target="_blank" rel="noreferrer noopener">creating a list</a>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">your_list = [1, 2, 3, 4]</pre>
<p>Some handy list methods are:</p>
<ul>
<li><code><a href="https://blog.finxter.com/python-list-append/" data-type="post" data-id="6605" target="_blank" rel="noreferrer noopener">append(x)</a></code>: Adds x to the end of the list</li>
<li><code><a href="https://blog.finxter.com/python-list-extend/" data-type="post" data-id="6741" target="_blank" rel="noreferrer noopener">extend(iterable)</a></code>: Adds items from iterable to the list</li>
<li><code><a href="https://blog.finxter.com/python-list-insert-method/" data-type="post" data-id="6758" target="_blank" rel="noreferrer noopener">insert(i, x)</a></code>: Inserts x at index i</li>
<li><code><a href="https://blog.finxter.com/python-list-remove/" data-type="post" data-id="6796" target="_blank" rel="noreferrer noopener">remove(x)</a></code>: Removes the first item with the value <code>x</code></li>
</ul>
<p>Feel free to dive into our full guide on lists here:</p>
<figure class="wp-block-image size-full"><a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener"><img decoding="async" loading="lazy" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-298.png" alt="" class="wp-image-1324290" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-298.png 1024w, https://blog.finxter.com/wp-content/uplo...00x169.png 300w, https://blog.finxter.com/wp-content/uplo...68x432.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></figure>
<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener">The Ultimate Guide to Python Lists</a></p>
<h3 class="wp-block-heading">Tuple</h3>
<p class="has-global-color-8-background-color has-background">A <a href="https://docs.python.org/3/library/stdtypes.html#tuples">Tuple</a> is an immutable sequence type. It’s similar to a list but cannot be modified once created. This makes tuples ideal for storing fixed sets of data. </p>
<p>Example of creating a tuple:</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="">your_tuple = (1, 2, 3)</pre>
<p>Since it’s immutable, fewer methods are available compared to lists:</p>
<ul>
<li><code>count(x)</code>: Counts the occurrences of <code>x</code> in the tuple</li>
<li><code>index(x)</code>: Finds the index of the first occurrence of <code>x</code></li>
</ul>
<p>Again, we have created a full guide on tuples here:</p>
<figure class="wp-block-image size-full"><a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" target="_blank" rel="noreferrer noopener"><img decoding="async" loading="lazy" width="768" height="432" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-299.png" alt="" class="wp-image-1324294" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-299.png 768w, https://blog.finxter.com/wp-content/uplo...00x169.png 300w" sizes="(max-width: 768px) 100vw, 768px" /></a></figure>
<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" data-type="URL" data-id="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" target="_blank" rel="noreferrer noopener">The Ultimate Guide to Python Tuples</a></p>
<h3 class="wp-block-heading">Set</h3>
<p class="has-global-color-8-background-color has-background">A set is an unordered collection of unique elements. Sets can help you manage distinct items, and they can be mutable or immutable (frozenset). </p>
<p>Example of <a href="https://blog.finxter.com/how-to-create-a-python-set-of-size-n/" data-type="post" data-id="722660" target="_blank" rel="noreferrer noopener">creating a set</a>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">your_set = {1, 2, 3, 3}</pre>
<p>A few useful set operations include:</p>
<ul>
<li><code><a href="https://blog.finxter.com/python-set-add/" data-type="post" data-id="27986" target="_blank" rel="noreferrer noopener">add(x)</a></code>: Adds x to the set</li>
<li><code><a href="https://blog.finxter.com/python-set-remove/" data-type="post" data-id="28012" target="_blank" rel="noreferrer noopener">remove(x)</a></code>: Removes x from the set</li>
<li><code><a href="https://blog.finxter.com/python-set-union/" data-type="post" data-id="28003" target="_blank" rel="noreferrer noopener">union(s)</a></code>: Returns the union of the set and s</li>
<li><code><a href="https://blog.finxter.com/python-set-intersection/" data-type="post" data-id="28024" target="_blank" rel="noreferrer noopener">intersection(s)</a></code>: Returns the intersection of the set and s</li>
</ul>
<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/sets-in-python/" data-type="URL" data-id="https://blog.finxter.com/sets-in-python/" target="_blank" rel="noreferrer noopener">The Ultimate Guide to Python Sets</a></p>
<h3 class="wp-block-heading">Dict</h3>
<p class="has-global-color-8-background-color has-background">The dictionary, or <code>dict</code>, is a mutable mapping type. This container allows you to store key-value pairs efficiently. </p>
<p>Example of <a href="https://blog.finxter.com/python-dictionary-how-to-create-add-replace-retrieve-remove/" data-type="post" data-id="36698" target="_blank" rel="noreferrer noopener">creating a <code>dict</code></a>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">your_dict = {'a': 1, 'b': 2, 'c': 3}</pre>
<p>Some helpful dict methods are:</p>
<ul>
<li><code>get(key, default)</code>: Gets the value for the key or returns the default value if not found</li>
<li><code>update(iterable)</code>: Merges the key-value pairs from iterable into the dictionary</li>
<li><code>pop(key, default)</code>: Removes and returns the value for the key or returns the default value if not found</li>
</ul>
<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank" rel="noreferrer noopener">The Ultimate Guide to Python Dictionaries</a></p>
<p>That’s a quick rundown of Python’s basic built-in container types!</p>
<h2 class="wp-block-heading">Advanced Container Types from Collections Module</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="602" height="941" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-302.png" alt="" class="wp-image-1324381" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-302.png 602w, https://blog.finxter.com/wp-content/uplo...92x300.png 192w" sizes="(max-width: 602px) 100vw, 602px" /></figure>
</div>
<p>The Python built-in containers, such as list, tuple, and dictionary, can be sufficient for many cases. However, when you need more specialized or high-performance containers, the <code><a href="https://blog.finxter.com/how-to-check-collections-package-version-in-python/" data-type="post" data-id="479229" target="_blank" rel="noreferrer noopener">collections</a></code> module comes to the rescue <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4aa.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>
<p>Let’s explore some of these advanced container types:</p>
<h3 class="wp-block-heading">Namedtuple</h3>
<p>Ever struggled with using tuples to store data, leading to unreadable and error-prone code? <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f914.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The <a href="https://towardsdatascience.com/pythons-collections-module-high-performance-container-data-types-cb4187afb5fc"><code>namedtuple</code></a> class is your answer! Namedtuples are similar to regular tuples, but each element has a name for better readability and maintenance <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from collections import namedtuple Person = namedtuple("Person", ["name", "age", "city"])
person1 = Person("Alice", 30, "New York")
print(person1.name) # Output: Alice
</pre>
<p>Now, you can access tuple elements by name instead of index, making your code more readable and less error-prone <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f44c.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>
<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-namedtuple/" data-type="URL" data-id="https://blog.finxter.com/python-namedtuple/" target="_blank" rel="noreferrer noopener">Python Named Tuple Methods</a></p>
<h3 class="wp-block-heading">Deque</h3>
<p>If you need a high-performance, double-ended queue, look no further than the <code><a href="https://docs.python.org/3/library/collections.html" target="_blank" rel="noreferrer noopener">deque</a></code> class. Deques allow you to efficiently append or pop items from both ends of the queue, which can be useful in various applications, such as maintaining a fixed-size history of events <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f570.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from collections import deque dq = deque(maxlen=3)
for i in range(5): dq.append(i) print(dq) # Output:
# deque([0], maxlen=3)
# deque([0, 1], maxlen=3)
# deque([0, 1, 2], maxlen=3)
# deque([1, 2, 3], maxlen=3)
# deque([2, 3, 4], maxlen=3)
</pre>
<p>With deque, you can keep your data structures efficient and clean <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f60e.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>
<h3 class="wp-block-heading">ChainMap</h3>
<p>Do you have multiple dictionaries that you want to treat as a single unit? The <a href="https://docs.python.org/3/library/collections.html">ChainMap</a> class can help! It allows you to link several mappings together, making it easy to search, update or delete items across dictionaries <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4da.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from collections import ChainMap dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
chain_map = ChainMap(dict1, dict2)
print(chain_map["b"]) # Output: 2, as it takes the value from the first dictionary
</pre>
<p>With ChainMap, you can work with multiple dictionaries as if they were one, simplifying your code and making it more efficient <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f609.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>
<h3 class="wp-block-heading">Counter</h3>
<p>Counting items in a collection can be a repetitive task. Luckily, the <a href="https://datagy.io/python-collections/">Counter</a> class can help you keep track of elements and their counts with ease <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4af.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from collections import Counter data = [1, 2, 3, 2, 1, 3, 1, 1]
count = Counter(data)
print(count) # Output: Counter({1: 4, 2: 2, 3: 2})
</pre>
<p>Now you can easily count items in your collections, making your code more concise and efficient <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f680.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>
<h3 class="wp-block-heading">OrderedDict</h3>
<p>If you need a dictionary that maintains the insertion order of items, the <code><a href="https://blog.finxter.com/how-to-get-first-key-value-in-a-dictionary/" data-type="post" data-id="514603" target="_blank" rel="noreferrer noopener">OrderedDict</a></code> class is perfect for you! Although <a href="https://blog.finxter.com/how-to-check-your-python-version/" data-type="post" data-id="1371" target="_blank" rel="noreferrer noopener">Python 3.7+</a> dictionaries maintain order by default, <code>OrderedDict</code> can be useful when working with older versions or when you want to explicitly show that order matters <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4dd.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from collections import OrderedDict od = OrderedDict()
od["a"] = 1
od["b"] = 2
od["c"] = 3
print(list(od.keys())) # Output: ['a', 'b', 'c']
</pre>
<p><code>OrderedDict</code> ensures that your code behaves consistently across Python versions and emphasizes the importance of insertion order <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f31f.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>
<h3 class="wp-block-heading">Defaultdict</h3>
<p>When working with dictionaries, do you often find yourself initializing default values? The <code><a href="https://datagy.io/python-collections/" target="_blank" rel="noreferrer noopener">defaultdict</a></code> class can automate that for you! Just provide a default factory function, and <code>defaultdict</code> will create default values for missing keys on the fly <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2728.png" alt="✨" class="wp-smiley" style="height: 1em; max-height: 1em;" />:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from collections import defaultdict dd = defaultdict(list)
dd["a"].append(1)
dd["b"].append(2)
dd["a"].append(3) print(dd) # Output: defaultdict(, {'a': [1, 3], 'b': [2]})
</pre>
<p>With <code>defaultdict</code>, you can keep your code free of repetitive default value initializations and make your code more Pythonic <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f40d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="627" height="942" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-303.png" alt="" class="wp-image-1324382" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-303.png 627w, https://blog.finxter.com/wp-content/uplo...00x300.png 200w" sizes="(max-width: 627px) 100vw, 627px" /></figure>
</div>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<p>Feel free to check out our cheat sheets on Python, OpenAI, and Blockchain topics:</p>
<p>Also, you may enjoy this article:</p>
<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/21-most-profitable-programming-languages-in-2023/" data-type="post" data-id="404278" target="_blank" rel="noreferrer noopener">21 Most Profitable Programming Languages</a></p>
</div>


https://www.sickgaming.net/blog/2023/04/...ick-guide/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016