Dictionary: creating, adding, accessing, removing elements; methods (get(), pop(), popitem(), clear(), copy())

Python dictionaries replace sequential numeric indexing with label-based lookup, letting you retrieve data values instantly via distinct keys.

11 min read · 12 cards · 3 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Breaking Free from Index Numbers

In your Semester 1 BCA104 C labs, if you wanted to track how much money you spent on different categories like 'food', 'travel', or 'laundry', you had to maintain two separate arrays or create a custom structure with complex search loops. If you wanted to look up the food expense, you had to loop through a string array, find the match index, and use that same index number on a separate numeric array. Why does Python discard this clumsy structural matching, allowing you to link values directly to meaningful textual labels?

Theory

The College Locker Room

Think of a list or an array like a long line of identical benches numbered 0, 1, 2, and 3. To find an item, you must know its exact bench position. A Python dictionary, however, is like a wall of college campus lockers. Each locker does not care about its sequence number; instead, it has a distinct painted name label on the door like 'Samosa', 'Chai', or 'Bus'. You do not look up an expense by saying 'give me item 2'; you simply walk up to the door labeled 'Samosa', turn the key, and pull out the price stored inside.

Theory

Dictionary Anatomy Formally

A dictionary in Python is an unordered, mutable collection of data elements stored as associative key-value pairs wrapped in curly braces {}. Every entry is mapped as key: value, where keys act as custom labels to access their corresponding values. Dictionaries enforce strict key uniqueness: while values can be duplicated as much as you like, keys must be completely unique and immutable data types (like strings, integers, or tuples). Accessing an element uses bracket syntax (dict[key]) or specialized extraction methods.

At a glance

Table 1: Essential Python dictionary methods for data lookup and element removal.

Method ToolAction Performed on MemoryKey-Missing Behavior
ledger.get(key, default)Safely retrieves a value for a specific key.Returns the default value (or None) without crashing.
ledger.pop(key)Removes the specified key and returns its value.Raises a KeyError unless a default fallback is supplied.
ledger.popitem()Removes and returns the last inserted key-value tuple.Raises a KeyError if called on an empty dictionary.
ledger.copy()Generates a shallow clone copy of the dictionary.Creates a fresh dictionary block in memory.
ledger.clear()Erases all key-value entries inside the dictionary.Leaves behind an empty dictionary object {}.

Theory

Worked Example: Building the Expense Hub

Let us look at how our PocketMoney system tracks category budgets using a dictionary structure. We will initialize a dictionary, add new tracking metrics, demonstrate the safe get method, and pop an item cleanly out of memory.

Practical

PocketMoney Dictionary Controller

# Step 1: Initializing a baseline expense ledger
expense_ledger = {"samosa": 30, "travel": 50}

# Step 2: Adding a new key-value pair dynamically
expense_ledger["stationery"] = 120

# Step 3: Overwriting an existing key value
expense_ledger["samosa"] = 35

# Step 4: Accessing values safely via get()
safe_fetch = expense_ledger.get("laundry", 0)

# Step 5: Popping a key-value entry out completely
travel_cost = expense_ledger.pop("travel")

print("Final Ledger State:", expense_ledger)
print("Safe Fetch (laundry):", safe_fetch)
print("Popped Travel Cost:", travel_cost)

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Think first

Trace the Ledger Mutations

Analyze the Python tracking script above. What exact mappings will remain inside expense_ledger when it prints out to the screen? Work out the math and keys carefully.

Show the answer

The script will output:

Final Ledger State: {'samosa': 35, 'stationery': 120}

Safe Fetch (laundry): 0

Popped Travel Cost: 50

Why? Let us trace it: Base dictionary is {'samosa': 30, 'travel': 50}. Adding 'stationery' expands it. Overwriting 'samosa' changes its value from 30 to 35. expense_ledger.get('laundry', 0) finds no 'laundry' key, so it returns the fallback value 0 without crashing. Finally, pop('travel') extracts 50 and removes the 'travel' key entirely, leaving behind two pairs.

Quiz

What happens if a programmer tries to access a missing key using standard bracket notation, such as print(expense_ledger["entertainment"]), when that key doesn't exist?

  1. It returns None automatically.
  2. It prints out a blank string "".
  3. It throws a KeyError and crashes the program.
  4. It appends the key with a default value of 0.
Show the answer

It throws a KeyError and crashes the program.

Using direct bracket notation like dict[key] forces Python to look for that key cell immediately. If the key is not present inside the collection, the interpreter halts execution and raises a KeyError exception. To avoid this crash, use the .get() method instead!

Quiz

Consider this declaration: data = {"ID": 101, "ID": 202}. What will be the value of data["ID"] when compiled inside a script?

  1. 101
  2. 202
  3. An list array containing [101, 202]
  4. It throws a SyntaxError because duplicate keys are explicitly banned.
Show the answer

202

Python dictionary keys must be completely unique. If you declare a dictionary with duplicate keys, Python does not throw a compile error; instead, it reads from left to right, and the final value overwrites all preceding ones. Thus, the key "ID" takes the latest value, which is 202.

Watch out

The Classic Trap: The Missing Key Bracket Crash

The most common mark-losing mistake in university viva examinations is using bracket notation my_dict[key] for search queries where the key might be absent. External user files or messy inputs frequently contain missing keys. Always use my_dict.get(key, fallback) instead of brackets when parsing unpredictable datasets to build crash-proof programs.

Theory

Connecting Dictionaries to Semester 3

Associative mapping is the bedrock of structured internet data exchange layers. In Semester 3 (BCA303), when you connect a Python web server application to an external API or load configuration profiles, data will arrive in the form of JSON (JavaScript Object Notation). Python reads JSON structures natively as nested dictionaries, allowing you to look up configurations using strings instead of positional numbers.

Summary

Key takeaways

  • Dictionaries are mutable collections that map unique, immutable keys directly onto data values.
  • Elements are stored as key-value pairs separated by colons inside a curly brace boundary.
  • Direct bracket lookups trigger a KeyError crash if the requested key is absent from the dictionary.
  • The get method extracts values safely, returning an alternative fallback value if the key is missing.
  • The pop and popitem methods mutate the dictionary by extracting values and deleting pairs permanently.
  • Memory Hook: Brackets crash on missing data, get handles defaults, keys remain absolute!

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Python Collections

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Dictionary: creating, adding, accessing, removing elements; methods (get(), pop(), popitem(), clear(), copy()) · Programming Skills · Gri-Learn