Estimated reading time: 4.1 mins read
Introduction
Python dictionaries are one of the most powerful data structures in Python. They allow you to store data in key-value pairs, making it easy to access, update, and manage information efficiently.
In this guide, we’ll explore everything a beginner needs to know about Python dictionaries, including creation, access, update, deletion, nested dictionaries, and interview questions.
What is a Python Dictionary?
A dictionary in Python is a collection of key-value pairs.
- Keys are unique and immutable (strings, numbers, tuples).
- Values can be any data type (string, number, list, tuple, dictionary, boolean, etc.).
- Dictionaries are mutable, meaning you can change, add, or delete items.
Example:
user_info = {
"name": "Nishtha",
"age": 25,
"learning": "Python"
}
Creating a Dictionary with Multiple Data Types
user_info = {
"key": "value",
"name": "Nishtha",
"subjects": ["Maths", "English", "Science"],
"topics": ("List", "Dict", "Maps"),
"learning": "Python",
"age": 25,
"is_girl": True,
"salary": 50000.89
}
print(user_info)
- Strings for simple values.
- List for multiple items.
- Tuple for fixed items.
- Boolean, integer, float for different data types.
Accessing Keys, Values, and Items
print('All keys:', user_info.keys())
print('All values:', user_info.values())
print('All key-value pairs:', user_info.items())
- Use
keys(),values(), anditems()to access dictionary elements. - Convert to list for easier indexing:
list(user_info.keys())
Accessing Values Safely
print(user_info["name"]) # Direct access
print(user_info.get("name")) # Safe access
print(user_info.get("phone", "Not available")) # Returns default if key doesn't exist
[]raises KeyError if key doesn’t exist.get()is safer and can return a default value.
Adding and Updating Keys
# Add a single key
user_info["city"] = "Delhi"
# Add multiple keys
user_info.update({"country": "India", "ID": "101"})
# Update existing key
user_info.update({"country": "Sweden"})
# Add multiple keys at once
user_info.update({"Occupation": "Software Engineer", "Nick name": "Nish"})
print(user_info)
- Assignment (
=) for single keys update()for multiple keys
Note:
update()modifies the dictionary in place and returns None
Removing Keys and Items
# Remove specific key and get its value
removed_age = user_info.pop("age")
print("Removed age:", removed_age)
# Remove the last inserted key-value pair
last_item = user_info.popitem()
print("Removed last item:", last_item)
# Delete a specific key
del user_info["salary"]
print(user_info)
# Clear all items
user_info.clear()
print("Dictionary after clear():", user_info)
pop(key)– removes a specific key and returns its valuepopitem()– removes the last inserted key-value pairdel key– deletes a specific keyclear()– empties the entire dictionary
Nested Dictionaries
A nested dictionary is a dictionary inside another dictionary.
student = {
"name": "Nishtha Jain",
"subjects": {
"Physics": 99,
"Chemistry": 98,
"Maths": 99
}
}
# Access nested value
print("Maths marks:", student["subjects"]["Maths"])
# Safe access
chemistry_marks = student.get("subjects", {}).get("Chemistry")
print("Chemistry marks (safe access):", chemistry_marks)
Iterating Through a Dictionary
# Iterate through keys
for key in user_info:
print(key)
# Iterate through values
for value in user_info.values():
print(value)
# Iterate through key-value pairs
for key, value in user_info.items():
print(key, ":", value)
Key Takeaways
- Dictionaries store data in key-value pairs.
- Access values using
[]orget(). - Add/update keys using assignment or
update(). - Remove keys/items using
pop(),popitem(),del, orclear(). - Dictionary keys must be unique and immutable.
- Values can be any data type, including lists, tuples, or nested dictionaries.
- Use
list()to convert keys, values, or items to lists.
Conclusion
Python dictionaries are flexible, powerful, and beginner-friendly. They are widely used in real-world applications, from storing user profiles to configuration data.
Important Interview Qs&As
Q1: What is a dictionary in Python?
A1: A dictionary is a collection of key-value pairs. Keys are unique, values can be any data type, and dictionaries are mutable.
Q2: How do you access a value?
A2: Using [] or get(). get() is safer for missing keys.
Q3: How do you add or update a key-value pair?
A3: Use assignment for single key (user_info["city"] = "Delhi") or update() for multiple keys.
Q4: How to safely access a key that might not exist?
A4: Use get(). Example: user_info.get("phone") returns None if key is missing.
Q5: Difference between [] and get()?
[] and get()?A5: [] raises KeyError if key doesn’t exist. get() returns None or a default value.
Q6: How do you remove keys?
A6: Use pop(), popitem(), del, or clear().
Q7: How do you iterate through a dictionary?
A7: Use for loops on keys, values, or items:
for key, value in user_info.items():
print(key, value)
Q8: What is a nested dictionary?
A8: A dictionary inside another dictionary, useful for structured data.
Q9: Can dictionary keys be of any type?
A9: No. Keys must be immutable (strings, numbers, tuples).
Q10: How to check if a key exists?
A10: Use in keyword: if "name" in user_info:
Happy Learning !


Leave a Reply