🗝️ Python Dictionaries 

🔹 1. What is a Dictionary?

A dictionary is a collection of key–value pairs.
Each key is unique, and it maps to a specific value.

Python Dictionaries (With Examples) : A Comprehensive Tutorial

✅ Example:

student = {
   "name": "Sakshi",
   "branch": "CSE",
   "sgpa": 9.4
}
 

✅ Accessing:

print(student["name"])   # Sakshi
print(student["sgpa"])   # 9.4
 

🔹 2. Features of Dictionaries

PropertyDescription
Ordered (from Python 3.7+)Keys maintain insertion order
MutableYou can add/change values
Unique KeysDuplicate keys not allowed
DynamicCan grow or shrink at runtime

🔹 3. Creating Dictionaries

✅ Example:

# Method 1 – Using {}
person = {"name": "Riya", "age": 20, "city": "Dehradun"}

# Method 2 – Using dict() constructor
person = dict(name="Riya", age=20, city="Dehradun")
 

✅ Empty Dictionary:

data = {}

 

🔹 4. Accessing Dictionary Values

MethodExampleOutput
Using keystudent["name"]"Sakshi"
Using get()student.get("sgpa")9.4
get() with defaultstudent.get("roll", "Not Found")"Not Found"

✅ Example:

student = {"name": "Sakshi", "sgpa": 9.4}
print(student.get("branch", "CSE"))  # default value if key not found
 

🔹 5. Changing or Adding Elements

✅ Example:

student = {"name": "Sakshi", "sgpa": 9.4}
student["branch"] = "CSE"   # Add new key
student["sgpa"] = 9.5       # Modify value
print(student)
 

🔹 6. Removing Elements

MethodDescriptionExample
pop(key)Removes key & returns its valuestudent.pop("sgpa")
popitem()Removes last inserted itemstudent.popitem()
del dict[key]Deletes a keydel student["name"]
clear()Empties the dictionarystudent.clear()

✅ Example:

student = {"name": "Sakshi", "branch": "CSE"}
student.pop("branch")
print(student)  # {'name': 'Sakshi'}
 

🔹 7. Looping Through Dictionary

✅ Example:

student = {"name": "Sakshi", "sgpa": 9.4, "branch": "CSE"}

for key in student:
   print(key, ":", student[key])
 

✅ Other ways:

for key, value in student.items():
   print(key, "=", value)
 

🔹 8. Dictionary Methods

Python Dictionaries - A collection of key-value pairs - TechVidvan
MethodDescription
keys()Returns all keys
values()Returns all values
items()Returns list of (key, value) pairs
update()Merges two dictionaries
copy()Returns shallow copy

✅ Example:

student = {"name": "Sakshi", "sgpa": 9.4}
student.update({"branch": "CSE", "year": 3})
print(student)
 

🔹 9. Nested Dictionary

A dictionary inside another dictionary.

✅ Example:

students = {
   1: {"name": "Sakshi", "sgpa": 9.4},
   2: {"name": "Riya", "sgpa": 8.9}
}

print(students[1]["name"])   # Sakshi
 

🔹 10. Dictionary Comprehension (Shortcut)

✅ Example:

squares = {x: x**2 for x in range(1, 6)}
print(squares)  # {1:1, 2:4, 3:9, 4:16, 5:25}
 

✅ With condition:

even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares)
 

🔹 11. Membership Test

✅ Example:

student = {"name": "Sakshi", "branch": "CSE"}
print("name" in student)     # True
print("age" not in student)  # True
 

🔹 12. Built-in Functions with Dictionary

FunctionDescriptionExample
len()Number of key-value pairslen(student)
str()Converts to stringstr(student)
type()Returns typetype(student)

 

🧠 Mini Practice Programs

  1. Create a dictionary of student details and print all keys and values.
  2. Count frequency of each character in a string using dictionary.
  3. Merge two dictionaries into one.
  4. Print the student with highest marks using dictionary.
  5. Convert two lists (keys & values) into a dictionary.

 

✅ Example: Count character frequency

text = "banana"
freq = {}

for ch in text:
   freq[ch] = freq.get(ch, 0) + 1

print(freq)  # {'b':1, 'a':3, 'n':2}