<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yashmahalpure on Medium]]></title>
        <description><![CDATA[Stories by Yashmahalpure on Medium]]></description>
        <link>https://medium.com/@yashmahalpure23405?source=rss-ac5a32cbff5f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PawVgoI16YrsSKSm</url>
            <title>Stories by Yashmahalpure on Medium</title>
            <link>https://medium.com/@yashmahalpure23405?source=rss-ac5a32cbff5f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:52:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yashmahalpure23405/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Master Python Dictionaries: Essential Pre-Defined Functions, Core Properties, and Practical Usage]]></title>
            <link>https://medium.com/@yashmahalpure23405/master-python-dictionaries-essential-pre-defined-functions-core-properties-and-practical-usage-003a481506dd?source=rss-ac5a32cbff5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/003a481506dd</guid>
            <dc:creator><![CDATA[Yashmahalpure]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 11:42:03 GMT</pubDate>
            <atom:updated>2026-08-18T11:42:03.783Z</atom:updated>
            <content:encoded><![CDATA[<p>n Python programming, managing data effectively is one of the most critical skills you will build. While data structures like lists, tuples, and sets allow you to store collections of individual items or unique values, real-world software usually deals with <strong>labeled relationships</strong>.</p><p>Consider common real-world examples:</p><ul><li>Mapping a <strong>user ID</strong> to a <strong>user profile</strong></li><li>Mapping a <strong>product code</strong> to its <strong>unit price</strong></li><li>Mapping a <strong>country code</strong> to its <strong>capital city</strong></li><li>Storing configurations like <strong>host</strong>, <strong>port</strong>, and <strong>database credentials</strong></li></ul><p>In Python, the primary tool for representing these associations is the <strong>Dictionary (</strong><strong>dict)</strong> data type.</p><p>A dictionary is a built-in data type designed to store data in <strong>key-value pairs</strong>. It provides an intuitive, readable way to organize complex records and allows you to find any piece of information directly by name rather than searching through a list from start to finish.</p><p>This tutorial covers the complete basics of Python dictionaries: fundamental properties, creation techniques, access patterns, modifications, and every essential built-in method.</p><h3>1. Key Properties of Python Dictionaries</h3><p>Before writing operations, let’s examine the core characteristics that define how dictionaries work in Python:</p><ul><li><strong>Key-Value Pair Structure:</strong> Unlike lists or sets that hold standalone elements, every item inside a dictionary consists of two parts: a <strong>Key</strong> (the identifier) and a <strong>Value</strong> (the data linked to that identifier).</li><li><strong>Unique Keys:</strong> A dictionary cannot hold duplicate keys. Every key must appear only once. If you assign a new value to an existing key, the previous value is overwritten.</li><li><strong>Immutable Keys:</strong> Keys must belong to an immutable data type. This means you can use strings (&quot;id&quot;), integers (42), floats (3.14), or tuples ((1, 2)). You <strong>cannot</strong> use mutable objects like lists ([1, 2]), sets, or other dictionaries as keys.</li><li><strong>Arbitrary Values:</strong> Values have no restrictions. A value can be any data type: integer, float, string, boolean, list, tuple, set, custom object, or even another nested dictionary. Values can also be duplicated across different keys.</li><li><strong>Mutable Structure:</strong> Dictionaries are dynamic. You can add new key-value pairs, update existing ones, or delete items at any point in your program.</li><li><strong>Insertion Order Preservation:</strong> In modern Python (Python 3.7+), dictionaries preserve the exact order in which keys are inserted into the structure.</li></ul><h3>2. Creating Dictionaries in Python</h3><p>There are several straightforward ways to declare and initialize a dictionary based on your needs.</p><h3>Using Curly Braces {} (Literal Syntax)</h3><p>The most direct and readable way to create a dictionary is by wrapping comma-separated key: value pairs inside curly braces :</p><pre># Empty dictionary<br>empty_dict = {}<br><br># Dictionary with string keys and mixed values<br>student = {<br>    &quot;roll_no&quot;: 101,<br>    &quot;name&quot;: &quot;Shreyash&quot;,<br>    &quot;course&quot;: &quot;Computer Science&quot;,<br>    &quot;marks&quot;: 92.5,<br>    &quot;is_passed&quot;: True<br>}<br><br>print(student)<br>print(type(student))  # Output: &lt;class &#39;dict&#39;&gt;</pre><h3>Using the dict() Constructor</h3><p>Python provides a built-in dict() function for creating dictionaries :</p><pre># 1. Passing keyword arguments (keys are treated as strings)<br>employee = dict(id=504, name=&quot;Ananya&quot;, department=&quot;Operations&quot;, salary=75000)<br><br># 2. Passing a list of two-item tuples<br>coordinates = dict([(&quot;latitude&quot;, 18.5204), (&quot;longitude&quot;, 73.8567)])<br><br>print(employee)<br>print(coordinates)</pre><h3>Using dict.fromkeys() for Bulk Initialization</h3><p>If you have a collection of keys and want to initialize all of them with the same default starting value, use dict.fromkeys() :</p><pre># List of server service keys<br>services = [&quot;auth_service&quot;, &quot;billing_service&quot;, &quot;notification_service&quot;]<br><br># Initialize all with default status &quot;stopped&quot;<br>service_status = dict.fromkeys(services, &quot;stopped&quot;)<br><br>print(service_status)<br># Output: {&#39;auth_service&#39;: &#39;stopped&#39;, &#39;billing_service&#39;: &#39;stopped&#39;, &#39;notification_service&#39;: &#39;stopped&#39;}</pre><h3>3. Accessing Data in a Dictionary</h3><p>Python offers multiple approaches for retrieving values, each designed for different situations.</p><h3>Direct Access Using Square Brackets []</h3><p>You can access any value by writing the dictionary variable followed by the key enclosed in square brackets :</p><pre>book = {<br>    &quot;title&quot;: &quot;Python Basics&quot;,<br>    &quot;author&quot;: &quot;Guido van Rossum&quot;,<br>    &quot;pages&quot;: 350,<br>    &quot;price&quot;: 499<br>}<br><br>print(book[&quot;title&quot;])   # Output: Python Basics<br>print(book[&quot;author&quot;])  # Output: Guido van Rossum</pre><p><strong>Important Caveat:</strong> If you try to access a key that does not exist using square brackets, Python raises a KeyError and halts execution :</p><pre>print(book[&quot;publisher&quot;])  # Raises: KeyError: &#39;publisher&#39;</pre><h3>Safe Access Using the .get() Method</h3><p>The .get() method prevents program crashes when querying uncertain keys. If the key exists, it returns the value; if it does not, it returns None (or a custom default value) instead of raising an error.</p><pre>car = {<br>    &quot;brand&quot;: &quot;Toyota&quot;,<br>    &quot;model&quot;: &quot;Corolla&quot;,<br>    &quot;year&quot;: 2022<br>}<br><br># Key exists -&gt; returns the stored value<br>print(car.get(&quot;brand&quot;))  # Output: Toyota<br><br># Key does not exist -&gt; returns None<br>print(car.get(&quot;color&quot;))  # Output: None<br><br># Key does not exist -&gt; returns user-defined fallback message<br>print(car.get(&quot;color&quot;, &quot;Not Specified&quot;))  # Output: Not Specified</pre><h3>Checking Key Existence with the in Operator</h3><p>You can check whether a specific key is present in a dictionary using the in keyword before attempting to read it :</p><pre>inventory = {&quot;apples&quot;: 50, &quot;bananas&quot;: 30, &quot;oranges&quot;: 20}<br><br># Check if key is present<br>if &quot;apples&quot; in inventory:<br>    print(f&quot;Apples available: {inventory[&#39;apples&#39;]}&quot;)<br><br># Check if key is absent<br>if &quot;grapes&quot; not in inventory:<br>    print(&quot;Grapes are currently out of stock.&quot;)</pre><h3>4. Modifying, Updating, and Adding Elements</h3><p>Because dictionaries are mutable, you can freely change their contents throughout the lifecycle of a script.</p><h3>Adding New Keys and Updating Existing Values</h3><p>Assignment syntax (dict[key] = value) works for both inserting new pairs and modifying existing ones :</p><pre>profile = {&quot;name&quot;: &quot;Rohan&quot;, &quot;role&quot;: &quot;Developer&quot;}<br><br># Adding a new key-value pair<br>profile[&quot;city&quot;] = &quot;Pune&quot;<br><br># Updating an existing value<br>profile[&quot;role&quot;] = &quot;Senior Developer&quot;<br><br>print(profile)<br># Output: {&#39;name&#39;: &#39;Rohan&#39;, &#39;role&#39;: &#39;Senior Developer&#39;, &#39;city&#39;: &#39;Pune&#39;}</pre><h3>Merging Dictionaries with .update()</h3><p>The .update() method takes another dictionary or an iterable of key-value pairs and merges it into the target dictionary :</p><pre>base_config = {&quot;theme&quot;: &quot;light&quot;, &quot;font_size&quot;: 14, &quot;auto_save&quot;: True}<br>user_preferences = {&quot;theme&quot;: &quot;dark&quot;, &quot;font_family&quot;: &quot;Fira Code&quot;}<br><br># Apply user settings onto base settings<br>base_config.update(user_preferences)<br><br>print(base_config)<br># Output: {&#39;theme&#39;: &#39;dark&#39;, &#39;font_size&#39;: 14, &#39;auto_save&#39;: True, &#39;font_family&#39;: &#39;Fira Code&#39;}</pre><h3>Setting Defaults with .setdefault()</h3><p>The .setdefault() method searches for a key:</p><ul><li>If the key exists, it returns its current value without changing anything.</li><li>If the key does not exist, it inserts the key with the provided default value and returns that value.</li></ul><pre>settings = {&quot;volume&quot;: 80}<br><br># Key exists: returns existing value (80)<br>current_vol = settings.setdefault(&quot;volume&quot;, 50)<br>print(&quot;Volume:&quot;, current_vol)  # Output: 80<br><br># Key does not exist: inserts &quot;brightness&quot;: 70 and returns 70<br>current_bright = settings.setdefault(&quot;brightness&quot;, 70)<br>print(&quot;Brightness:&quot;, current_bright)  # Output: 70<br><br>print(settings)<br># Output: {&#39;volume&#39;: 80, &#39;brightness&#39;: 70}</pre><h3>5. Removing Elements from a Dictionary</h3><p>Python provides several methods to delete individual items or clear an entire dictionary.</p><h3>1. The .pop() Method</h3><p>Removes the item with the specified key and returns its value. You can supply an optional fallback default to prevent a KeyError if the key is missing.</p><pre>fruits = {&quot;apple&quot;: 10, &quot;banana&quot;: 5, &quot;cherry&quot;: 25}<br><br># Pop existing item<br>removed_count = fruits.pop(&quot;banana&quot;)<br>print(&quot;Removed count:&quot;, removed_count)  # Output: 5<br><br># Pop missing item with fallback<br>unknown = fruits.pop(&quot;mango&quot;, &quot;Key not found&quot;)<br>print(&quot;Result:&quot;, unknown)  # Output: Key not found<br><br>print(fruits)  # Output: {&#39;apple&#39;: 10, &#39;cherry&#39;: 25}</pre><h3>2. The .popitem() Method</h3><p>Removes and returns the <strong>most recently added</strong> key-value pair as a (key, value) tuple.</p><pre>tasks = {1: &quot;Write code&quot;, 2: &quot;Run tests&quot;, 3: &quot;Deploy app&quot;}<br><br>last_task = tasks.popitem()<br>print(&quot;Removed last task:&quot;, last_task)  # Output: (3, &#39;Deploy app&#39;)<br>print(tasks)                           # Output: {1: &#39;Write code&#39;, 2: &#39;Run tests&#39;}</pre><h3>3. The del Statement</h3><p>The del keyword permanently removes a key-value pair from the dictionary without returning the value :</p><pre>user_account = {&quot;username&quot;: &quot;admin&quot;, &quot;temp_token&quot;: &quot;abc999&quot;, &quot;status&quot;: &quot;active&quot;}<br><br># Delete token<br>del user_account[&quot;temp_token&quot;]<br><br>print(user_account)<br># Output: {&#39;username&#39;: &#39;admin&#39;, &#39;status&#39;: &#39;active&#39;}</pre><h3>4. The .clear() Method</h3><p>Removes all elements from the dictionary, leaving it completely empty :</p><pre>cache = {&quot;session_1&quot;: &quot;data_a&quot;, &quot;session_2&quot;: &quot;data_b&quot;}<br><br>cache.clear()<br>print(cache)  # Output: {}</pre><h3>5. Iterating Over Dictionaries (Keys, Values, and Items)</h3><p>You can loop through a dictionary to inspect its keys, its values, or both together.</p><pre>marks = {&quot;Math&quot;: 95, &quot;Physics&quot;: 88, &quot;Chemistry&quot;: 91}</pre><h3>Iterating Over Keys</h3><p>By default, looping directly over a dictionary iterates through its keys. You can also make this explicit using .keys():</p><pre># Default iteration<br>for subject in marks:<br>    print(&quot;Subject:&quot;, subject)<br><br># Explicit iteration using .keys()<br>for subject in marks.keys():<br>    print(&quot;Subject:&quot;, subject)</pre><h3>Iterating Over Values</h3><p>Use the .values() method when you only need the data values :</p><pre>for score in marks.values():<br>    print(&quot;Score:&quot;, score)</pre><h3>Iterating Over Key-Value Pairs (Items)</h3><p>The most idiomatic way to loop through both keys and values simultaneously is with .items(), using tuple unpacking :</p><pre>for subject, score in marks.items():<br>    print(f&quot;Subject: {subject} | Score: {score}&quot;)</pre><h3>6. Copying Dictionaries</h3><p>When working with mutable structures, assigning one dictionary variable to another does not create a new copy; it only creates a new reference pointing to the exact same object in memory.</p><h3>Assignment vs. .copy()</h3><pre># 1. Assignment (Same Reference)<br>original = {&quot;x&quot;: 10, &quot;y&quot;: 20}<br>alias = original<br>alias[&quot;x&quot;] = 999<br>print(original)  # Output: {&#39;x&#39;: 999, &#39;y&#39;: 20} -&gt; Original was modified!<br><br># 2. Shallow Copy with .copy()<br>fresh_original = {&quot;x&quot;: 10, &quot;y&quot;: 20}<br>independent_copy = fresh_original.copy()<br>independent_copy[&quot;x&quot;] = 500<br><br>print(fresh_original)     # Output: {&#39;x&#39;: 10, &#39;y&#39;: 20} -&gt; Untouched<br>print(independent_copy)   # Output: {&#39;x&#39;: 500, &#39;y&#39;: 20}</pre><h3>7. Nested Dictionaries (Working with Complex Records)</h3><p>A dictionary can contain other dictionaries as values. This is commonly used when handling JSON records, API responses, or relational records.</p><pre>students_database = {<br>    &quot;STD_01&quot;: {<br>        &quot;name&quot;: &quot;Amit&quot;,<br>        &quot;age&quot;: 20,<br>        &quot;grades&quot;: {&quot;midterm&quot;: 85, &quot;final&quot;: 90}<br>    },<br>    &quot;STD_02&quot;: {<br>        &quot;name&quot;: &quot;Sneha&quot;,<br>        &quot;age&quot;: 21,<br>        &quot;grades&quot;: {&quot;midterm&quot;: 92, &quot;final&quot;: 95}<br>    }<br>}<br><br># Accessing nested fields by chaining square brackets<br>amit_name = students_database[&quot;STD_01&quot;][&quot;name&quot;]<br>sneha_final = students_database[&quot;STD_02&quot;][&quot;grades&quot;][&quot;final&quot;]<br><br>print(f&quot;Student: {amit_name}&quot;)               # Output: Student: Amit<br>print(f&quot;Sneha&#39;s Final Grade: {sneha_final}&quot;)  # Output: Sneha&#39;s Final Grade: 95</pre><h3>8. Dictionary Comprehensions</h3><p>Dictionary comprehension provides a clean, single-line syntax to build dictionaries from existing iterables.</p><pre># Format: {key_expression: value_expression for item in iterable if condition}<br><br># 1. Generate squares for numbers 1 through 5<br>squares = {n: n**2 for n in range(1, 6)}<br>print(squares)  <br># Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}<br><br># 2. Filter even numbers only<br>even_squares = {n: n**2 for n in range(1, 11) if n % 2 == 0}<br>print(even_squares)<br># Output: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}<br><br># 3. Transform prices from INR to USD (approximated)<br>prices_inr = {&quot;shirt&quot;: 1500, &quot;shoes&quot;: 3500, &quot;watch&quot;: 2500}<br>prices_usd = {item: round(price / 83, 2) for item, price in prices_inr.items()}<br>print(prices_usd)<br># Output: {&#39;shirt&#39;: 18.07, &#39;shoes&#39;: 42.17, &#39;watch&#39;: 30.12}</pre><h3>9. Complete Built-In Methods Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/0*LjVoXRkmkz43qvWA" /></figure><ul><li><strong>clear()</strong> — d.clear()</li><li><em>Description:</em> Removes all elements from the dictionary.</li><li><strong>copy()</strong> — d.copy()</li><li><em>Description:</em> Returns a shallow copy of the dictionary.</li><li><strong>fromkeys()</strong> — dict.fromkeys(seq, val)</li><li><em>Description:</em> Creates a new dictionary with keys from sequence and a uniform value.</li><li><strong>get()</strong> — d.get(key, default)</li><li><em>Description:</em> Returns value if key exists; otherwise returns default (None).</li><li><strong>items()</strong> — d.items()</li><li><em>Description:</em> Returns a dynamic view of all (key, value) pairs.</li><li><strong>keys()</strong> — d.keys()</li><li><em>Description:</em> Returns a dynamic view of all keys.</li><li><strong>pop()</strong> — d.pop(key, default)</li><li><em>Description:</em> Removes the specified key and returns its corresponding value.</li><li><strong>popitem()</strong> — d.popitem()</li><li><em>Description:</em> Removes and returns the last inserted (key, value) tuple.</li><li><strong>setdefault()</strong> — d.setdefault(key, val)</li><li><em>Description:</em> Returns value if key exists; inserts key with val if missing.</li><li><strong>update()</strong> — d.update(other)</li><li><em>Description:</em> Updates dictionary with key-value pairs from another dictionary or iterable.</li><li><strong>values()</strong> — d.values()</li><li><em>Description:</em> Returns a dynamic view of all values.</li></ul><h3>Conclusion</h3><p>The Python <strong>Dictionary</strong> is one of the language’s most versatile and indispensable data types. Mastering key properties, safe retrieval methods like .get(), clean iteration using .items(), and compact dictionary comprehensions will allow you to write clean, maintainable, and idiomatic Python code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=003a481506dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>