A dictionary in Python is an unordered, mutable, and indexed collection that stores data in the form of key-value pairs.
Each key in a dictionary must be unique and immutable, while values can be of any data type and may repeat.

Dictionaries are one of the most important and flexible data structures in Python — often used for mapping data, storing configurations, or representing JSON-like structures.


🔹 Key Properties of Dictionaries

  • Unordered → No guaranteed order (insertion order preserved since Python 3.7).
  • Mutable → You can add, update, or remove elements.
  • Key-Value Pairs → Each item has a unique key associated with a value.
  • Keys must be immutable → Can be strings, numbers, or tuples (but not lists).
  • Fast lookups → Optimized for fast searching via keys (hashing).

🔹 Common Dictionary Functions & Methods

Function / MethodDescriptionExample
len(dict)Returns the number of key-value pairs.len({'a':1,'b':2}) → 2
dict.keys()Returns all keys.my_dict.keys()
dict.values()Returns all values.my_dict.values()
dict.items()Returns key-value pairs as tuples.my_dict.items()
dict.get(key[, default])Returns the value for a key, or default if not found.my_dict.get('x', 0)
dict.update(other_dict)Updates dictionary with another dictionary or iterable.a.update(b)
dict.pop(key[, default])Removes and returns value for the given key.my_dict.pop('age')
dict.popitem()Removes and returns the last inserted key-value pair.my_dict.popitem()
dict.clear()Removes all items from the dictionary.my_dict.clear()
dict.copy()Returns a shallow copy of the dictionary.b = a.copy()
dict.fromkeys(keys[, value])Creates a dictionary from a sequence of keys with a common value.dict.fromkeys(['a','b'], 0)
dict.setdefault(key[, default])Returns value of key; if not found, inserts key with default.my_dict.setdefault('age', 25)

🧩 Example 1: Creating and Accessing Dictionary Elements

person = {"name": "Dheeraj", "age": 24, "city": "Delhi"}
print("Name:", person["name"])
print("Age:", person["age"])

Output:

Name: Dheeraj
Age: 24

🧩 Example 2: Adding and Updating Items

person = {"name": "Dheeraj", "age": 24}
person["city"] = "Delhi"         # Add new key-value pair
person["age"] = 25               # Update existing key
print(person)

Output:

{'name': 'Dheeraj', 'age': 25, 'city': 'Delhi'}

🧩 Example 3: Using get() and update()

student = {"name": "Alice", "marks": 85}
print("Marks:", student.get("marks"))
print("Grade:", student.get("grade", "Not Assigned"))  # Default value

student.update({"grade": "A", "age": 20})
print("Updated Dictionary:", student)

Output:

Marks: 85
Grade: Not Assigned
Updated Dictionary: {'name': 'Alice', 'marks': 85, 'grade': 'A', 'age': 20}

🧩 Example 4: Removing Items

data = {"a": 1, "b": 2, "c": 3}
data.pop("b")
data.popitem()  # Removes last item
print("After Removal:", data)

Output:

After Removal: {'a': 1}

🧩 Example 5: Iterating Over a Dictionary

employee = {"name": "John", "role": "Developer", "salary": 60000}

for key, value in employee.items():
    print(f"{key} → {value}")

Output:

name → John
role → Developer
salary → 60000

🧩 Example 6: Using fromkeys() and setdefault()

keys = ["a", "b", "c"]
new_dict = dict.fromkeys(keys, 0)
print("FromKeys:", new_dict)

info = {"name": "Dheeraj"}
info.setdefault("age", 24)
print("With setdefault:", info)

Output:

FromKeys: {'a': 0, 'b': 0, 'c': 0}
With setdefault: {'name': 'Dheeraj', 'age': 24}

🧩 Example 7: Copying and Clearing a Dictionary

car = {"brand": "BMW", "model": "X5", "year": 2024}
copy_car = car.copy()
car.clear()

print("Original after clear:", car)
print("Copied Dictionary:", copy_car)

Output:

Original after clear: {}
Copied Dictionary: {'brand': 'BMW', 'model': 'X5', 'year': 2024}

🔹 In Summary

  • A dictionary stores key-value pairs and allows fast access using keys.
  • It is mutable, dynamic, and can hold heterogeneous data.
  • Common operations include adding, updating, deleting, and iterating over key-value pairs.
  • Useful in data mapping, JSON-like structures, and lookup operations.

✅ In short:

A Dictionary = {key: value} pairs → Fast, flexible, and powerful for structured data handling.


Scroll to Top