Python Dictionary Tutorial – Beginner to Advanced (2025 Guide)
Python dictionaries are one of the most powerful and flexible data types in the language. If you're coming from another programming background, think of them like hash maps or objects (in JavaScript).
In this guide, we’ll break down everything you need to know about dictionaries — from basics to advanced — in a way that's simple and practical for all levels.
What is a Dictionary in Python?
A dictionary in Python is a collection of key-value pairs.
- Each key is unique and maps to a value
- Keys must be immutable (strings, numbers, tuples)
- Values can be any type
- Unordered before Python 3.7, ordered since then
✅ Keys must be unique. Values can repeat.
Dictionaries are written using curly braces {}
.
How to Create a Dictionary
# Example: Creating a dictionary
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print(person)
Output:
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Creating an Empty Dictionary
Empty dictionary is a dictionary without any item in it.
empty_dict = {}
print(empty_dict) # Output: {}
🔍 Accessing Values in a Dictionary
print(person["name"]) # Output: Alice
print(person["age"]) # Output: 25
KeyError Example:
print(person["email"]) # ❌ Raises KeyError
✅ Safer Access with get()
print(person.get("email", "Not Provided")) # Output: Not Provided
✏️ Updating a Dictionary
person["age"] = 30 # Update
person["email"] = "alice@example.com" # Add
print(person)
❌ Deleting Dictionary Items
del person["city"] # Delete specific key
person.clear() # Clear all items
del person # Delete entire dictionary
Dictionary Key Rules
- Keys must be unique
- Keys must be immutable: strings, numbers, tuples ✅ — lists and sets ❌
d = {"a": 1, "a": 2}
print(d) # Output: {'a': 2}
Built-in Dictionary Functions
len(dict)
- Total number of key-value pairsstr(dict)
- String representationtype(dict)
- Shows the data type
print(len(person))
print(str(person))
print(type(person))
Useful Dictionary Methods
Method | Description |
---|---|
dict.clear() |
Removes all items |
dict.copy() |
Returns a shallow copy |
dict.fromkeys(keys, value) |
Creates dictionary from keys |
dict.get(key, default) |
Returns value or default |
key in dict |
Checks if key exists |
dict.items() |
List of (key, value) pairs |
dict.keys() |
Returns keys |
dict.values() |
Returns values |
dict.setdefault() |
Returns value or sets default |
dict.update(other) |
Updates dictionary |
🔄 Deprecated (Python 2 only)
# dict.has_key('x') → ❌ Use: 'x' in dict
✅ Practice Time
student = {
"name": "John",
"grades": [85, 92, 78],
"passed": True
}
# Add 'course'
# Update 'passed'
# Print keys and values
📌 What's Next?
👉 Read: Python Functions – Explained Simply
🎥 Want to See It in Action?
YouTube video is here: