Free Study Material

Dictionary In Python

Introduction

Lists and tuples locate a value by its numeric position. A dictionary locates a value by a name you choose yourself — a far more natural fit for data like a student's marks in different subjects.

Concept

A dictionary stores data as key-value pairs, written inside curly braces {}. Each key maps to exactly one value, and every key must be unique. A dictionary is mutable.

student = {"name": "Aisha", "marks": 91}

Keys must be an immutable type — commonly a string or number. Values can be anything.

Worked Example

marks = {"Physics": 85, "Chemistry": 78, "Maths": 92}

print(marks)
print(type(marks))
print(marks["Physics"])

marks maps each subject (the key) to a score (the value). type(marks) prints <class 'dict'>. marks["Physics"] reaches the value paired with "Physics", giving 85 — by key name, not by numeric position.

Note: {} on its own creates an empty dictionary, even though sets also use curly braces — Python always treats bare {} as a dictionary.

Explanation

A dictionary is the right structure specifically when data is naturally described by a label rather than a position — marks["Physics"] is more direct than needing to remember Physics happens to sit at some index of a separate list.

Summary

A dictionary stores key-value pairs in curly braces {}, with every key unique and immutable, and values of any type. A value is reached by its key (my_dict["key"]), not by numeric position.

Definition

A Dictionary is an unordered collection of items where each item consists of a Key and a Value. It is enclosed in Curly Braces { }.

The "Key-Value" Logic:

  • Key (Label): Must be Unique and Immutable (Strings, Numbers, Tuples). You use this to find data.
  • Value (Data): Can be Anything (Mutable or Immutable, Duplicates allowed). This is the actual data.
Example: { "Brand": "Nike", "Price": 5000 }

Syntax

my_dict = { "Key1" : Value1, "Key2" : Value2 }
# 1. Empty Dictionary
empty = {}

# 2. Student Record (Strings as Keys)
student = {
    "Name": "Rahul",
    "Age": 16,
    "Stream": "CS"
}
print("Student Data:", student)

# 3. Number Mapping (Integers as Keys)
rankings = {
    1: "Gold",
    2: "Silver",
    3: "Bronze"
}
print("Rank 1 Prize:", rankings[1])

Rules for Keys

  • Unique: You cannot have two keys with the same name. If you do, the second one overwrites the first.
  • Immutable: You can use a String, Number, or Tuple as a key. You cannot use a List (because lists can change).
# Rule 1: Duplicate Keys overwrite previous ones
data = {
    "Score": 100,
    "Score": 95   # This overwrites 100!
}
print("Duplicate Test:", data) 
# Output: {'Score': 95}

# Rule 2: Mutable Keys are Forbidden
# Uncommenting the next line causes an Error
# invalid = { ["A", "B"] : "List Key" } 
# TypeError: unhashable type: 'list'

Introduction

This topic covers reading a value safely, adding a new pair, and changing an existing one — the everyday operations a dictionary is used for.

Concept

  • my_dict[key] — returns the value for key. Raises KeyError if key doesn't exist.
  • my_dict.get(key) — returns the value for key, or None if it doesn't exist.
  • my_dict[key] = value — adds a new pair if key doesn't exist, or overwrites it if it does.

Worked Example

marks = {"Physics": 85, "Chemistry": 78}

print(marks.get("Maths"))

marks["Maths"] = 92
marks["Physics"] = 90

print(marks)

marks.get("Maths") returns None, since "Maths" isn't a key yet — no error. marks["Maths"] = 92 adds a brand-new pair. marks["Physics"] = 90 overwrites the existing value, since that key already exists. Final result: {'Physics': 90, 'Chemistry': 78, 'Maths': 92}.

Warning: marks["Maths"] (using [ ]) on a dictionary that doesn't yet have that key raises KeyError: 'Maths' — use .get() whenever a key's absence is a normal possibility.

Explanation

Whether my_dict[key] = value adds or overwrites depends only on whether key was already present — the same one line handles both cases, unlike a list, which needs separate operations for adding versus updating.

Summary

my_dict[key] reads a value and raises KeyError if missing; my_dict.get(key) reads a value and returns None instead. my_dict[key] = value both adds and overwrites, depending only on whether the key already existed.

Syntax: Retrieval

Method 1: Square Brackets
value = dict["Key"]

⚠️ Crashes (KeyError) if key not found.

Method 2: .get() (Safe)
value = dict.get("Key")

✅ Returns 'None' if key not found.

user = {
    "username": "coder123",
    "level": 5
}

# 1. Successful Access
print("User:", user["username"])  # Output: coder123

# 2. The Danger of Brackets
# print(user["score"])  <-- ERROR! KeyError: 'score'

# 3. The Safety of .get()
print("Score:", user.get("score")) # Output: None
print("Level:", user.get("level")) # Output: 5
prices = {"Apple": 100, "Banana": 40}
print("Original:", prices)

# Case A: Modifying (Key 'Apple' exists)
prices["Apple"] = 120
print("After Update:", prices)
# Result: Apple is now 120

# Case B: Adding (Key 'Mango' does not exist)
prices["Mango"] = 80
print("After Add:", prices)
# Result: Mango is added to the end
# Deleting a key
del prices["Banana"]
print("After Delete:", prices)
# Result: Banana is gone. Warning: Crashes if key isn't there!

Introduction

Beyond reading one key at a time, a dictionary has built-in methods for supplying a fallback value, merging in many pairs at once, and pulling out its keys, values, or pairs together.

Concept

  • get(key, default) — returns default instead of None when key is missing.
  • update(other_dict) — merges another dictionary's pairs in: existing keys get overwritten, new keys get added.
  • keys(), values(), items() — return all the keys, all the values, or all the key-value pairs (each as a tuple).

Worked Example

marks = {"Physics": 85, "Chemistry": 78}

print(marks.get("Maths", 0))

marks.update({"Maths": 92, "Physics": 88})
print(marks)

print(list(marks.keys()))
print(list(marks.values()))
print(list(marks.items()))

marks.get("Maths", 0) returns the fallback 0, since "Maths" isn't a key; marks itself is unchanged by get(). marks.update({"Maths": 92, "Physics": 88}) adds "Maths" and overwrites "Physics" in one call: {'Physics': 88, 'Chemistry': 78, 'Maths': 92}. list(marks.keys()) gives ['Physics', 'Chemistry', 'Maths']; list(marks.values()) gives [88, 78, 92]; list(marks.items()) gives [('Physics', 88), ('Chemistry', 78), ('Maths', 92)].

Note: keys(), values(), and items() return live view objects, not plain lists — wrapping them in list(), as above, takes a fixed snapshot.

Explanation

update() is the dictionary equivalent of a list's extend() — both merge one collection's contents into another in a single call, rather than one line per pair.

Summary

get(key, default) returns a fallback without changing the dictionary; update(other_dict) merges another dictionary's pairs in; keys(), values(), items() return live views of a dictionary's keys, values, or pairs.

What are Built-in Functions?

Built-in functions are pre-defined in Python. Unlike methods, these functions take the Dictionary Object as an argument inside parentheses. They are primarily used for creating dictionaries and measuring their size.

Key Functions for IP:

  • dict(): Used to initialize a dictionary or convert other sequences into a mapping.
  • len(): Calculates how many key-value pairs are currently stored.
  • del(): A keyword used as a function to remove specific keys or the entire dictionary from memory.
# Rule: dict() creates a dictionary from a list of tuples or keyword arguments
data = dict([("City", "Delhi"), ("Temp", 25)])
print("Created Dictionary:", data)
# Output: {'City': 'Delhi', 'Temp': 25}

# You can also use keyword arguments
scores = dict(Math=95, IP=98)
print("Scores:", scores)
# Output: {'Math': 95, 'IP': 98}
# Rule: len() counts the number of pairs, not individual elements
student = {"Name": "Amit", "Roll": 1, "Stream": "IP"}
print("Total Pairs:", len(student))
# Output: 3
# Rule: del can delete a specific key using its name
stock = {"Apples": 50, "Bananas": 20}
del stock["Bananas"]
print("After Deletion:", stock)
# Output: {'Apples': 50}

# Rule: del stock (without brackets) deletes the whole variable from memory

Introduction

This closing topic covers looping through a dictionary's contents, and the methods that remove data from one.

Concept

  • Traversal: for key in my_dict: visits every key; for key, value in my_dict.items(): visits both together.
  • pop(key) — removes key and returns its value.
  • popitem() — removes and returns the most recently added pair, as a tuple.
  • del my_dict[key] — removes key, returns nothing.
  • clear() — removes every pair.
  • len() — number of pairs.

Worked Example

marks = {"Physics": 85, "Chemistry": 78, "Maths": 92}

for subject, score in marks.items():
    print(subject, "scored", score)

removed = marks.pop("Chemistry")
print(removed, marks, len(marks))

The loop unpacks marks.items() directly into subject and score, printing each pair. marks.pop("Chemistry") removes that pair and returns 78; marks becomes {'Physics': 85, 'Maths': 92}, and len(marks) is 2.

Note: Looping directly over a dictionary (for key in my_dict:) visits keys only, never values — exactly why .items() exists for whenever both are needed together.

Explanation

pop(key) on a dictionary mirrors pop(index) on a list — both remove by identifying a specific location and hand back what was removed.

Summary

for key, value in my_dict.items(): traverses both together. pop(key) removes by key and returns the value; popitem() removes the most recently added pair; del my_dict[key] removes without returning anything; clear() empties the dictionary; len() counts its pairs.

Extraction Methods

In IP, we often need to separate the "labels" (keys) from the "data" (values). Python provides three primary methods to view different parts of a dictionary without changing them.

1. keys(), values(), and items()

These methods return view objects. This means if the dictionary changes, the view object updates automatically. They are essential for looping through data.

# Rule: .keys() returns only the labels, .values() returns only the data
inventory = {"Keyboard": 15, "Mouse": 22, "Monitor": 8}

print("Labels (Keys):", inventory.keys())
# Output: dict_keys(['Keyboard', 'Mouse', 'Monitor'])

print("Data (Values):", inventory.values())
# Output: dict_values([15, 22, 8])
# Rule: .items() returns pairs as tuples, perfect for 'for' loops
sales = {"Jan": 5000, "Feb": 4500}

print("All Pairs:", sales.items())
# Output: dict_items([('Jan', 5000), ('Feb', 4500)])

Maintenance Methods

To keep our data up to date, we use update() to add new information and clear() to reset our data collection.

# Rule: .update() merges a new dictionary into the current one
# Existing keys are overwritten, new keys are added
emp = {"Name": "Rahul", "Dept": "Sales"}
new_info = {"Dept": "IT", "Salary": 45000}

emp.update(new_info)
print("Updated Record:", emp)
# Output: {'Name': 'Rahul', 'Dept': 'IT', 'Salary': 45000}
# Rule: .clear() removes all items but the variable name still exists
temp_data = {"Mon": 32, "Tue": 34}
temp_data.clear()

print("After Clear:", temp_data)
# Output: {}

Want the full course?

Unlock all chapters, video lectures, and SQL practice exercises.

Get Full Access