Dictionaries - Python Basics

Dictionaries - Python Basics

When learning Python, one of the most powerful and commonly used data structures you’ll encounter is the Dictionary. A Python dictionary allows you to store and manage data in key-value pairs, making it ideal for tasks where fast lookups and organized data storage are required. In this educational guide, we’ll go step by step and learn everything about Python dictionaries with explanations, examples, tips, and exercises.


🔹 What is a Dictionary in Python?

A dictionary is a collection of items in Python where each item has two parts: a key and a value. Keys act like unique identifiers (like student IDs), while values are the data stored (like student names). You can think of it as a real-life dictionary: a word (key) maps to its meaning (value).


# Example of a dictionary
student = {
  "name": "Alice",
  "age": 21,
  "course": "Computer Science"
}

print(student)
# Output: {'name': 'Alice', 'age': 21, 'course': 'Computer Science'}

Here, name, age, and course are keys, while "Alice", 21, and "Computer Science" are their respective values.


✅ Characteristics of Python Dictionaries

Before diving deeper, let’s understand the key characteristics of Python dictionaries:

  • Key-Value Storage: Data is stored in pairs, which makes retrieval simple and fast.
  • Unique Keys: Keys must be unique. If you use the same key twice, the latest value will overwrite the old one.
  • Mutable: You can change, add, or remove items even after creating the dictionary.
  • Unordered (before Python 3.7): Dictionaries did not preserve order. From Python 3.7+, they maintain insertion order.
  • Keys must be immutable: You can use strings, numbers, or tuples as keys, but not lists or sets.

📌 Uses of Dictionaries

Dictionaries are extremely versatile in real-world applications. Here are some examples:

  • Storing user data: Store information such as name, age, email, etc.
  • Configuration settings: Save application settings like database connections.
  • Counting words: Count word frequency in a paragraph or document.
  • Mapping values: Map employee IDs to their names, or country codes to country names.
  • APIs and JSON: Data returned from web APIs is often in dictionary (JSON) format.

🔑 Access Dictionary Items

There are two ways to access values in a dictionary: using square brackets [] or the get() method.


student = {"name": "Alice", "age": 21, "course": "CS"}

# Access using key
print(student["name"])   # Output: Alice

# Access safely using get()
print(student.get("age"))   # Output: 21

# If key does not exist
print(student.get("city", "Not Found"))  # Output: Not Found

Note: Using get() is safer because it won’t throw an error if the key doesn’t exist.


✏️ Change Dictionary Items

Dictionaries are mutable, which means you can update the value of an existing key.


student = {"name": "Alice", "age": 21, "course": "CS"}

# Update values
student["age"] = 22
student["course"] = "Data Science"

print(student)
# Output: {'name': 'Alice', 'age': 22, 'course': 'Data Science'}

➕ Add Dictionary Items

You can add new key-value pairs to a dictionary simply by assigning them.


student["city"] = "New York"
print(student)
# Output: {'name': 'Alice', 'age': 22, 'course': 'Data Science', 'city': 'New York'}

➖ Remove Dictionary Items

Python provides multiple ways to remove dictionary items:


student = {"name": "Alice", "age": 22, "city": "New York"}

# Remove a specific item
student.pop("age")

# Remove using del
del student["city"]

# Remove last inserted item
student.popitem()

# Clear all items
student.clear()

🔁 Loop Through Dictionaries

Since dictionaries hold both keys and values, you can loop through them in different ways:


student = {"name": "Alice", "age": 22, "city": "New York"}

# Loop through keys
for key in student:
    print(key)

# Loop through values
for value in student.values():
    print(value)

# Loop through key-value pairs
for key, value in student.items():
    print(key, ":", value)

📄 Copy Dictionaries

If you want to copy a dictionary, don’t just use = because it creates a reference. Instead, use copy() or dict().


original = {"a": 1, "b": 2}

copy1 = original.copy()
copy2 = dict(original)

print(copy1, copy2)

📂 Nested Dictionaries

A dictionary can also contain another dictionary. This is called a nested dictionary and is very useful for structured data.


students = {
  "student1": {"name": "Alice", "age": 21},
  "student2": {"name": "Bob", "age": 22}
}

print(students["student1"]["name"])  # Output: Alice

⚙️ Dictionary Methods

Python provides many built-in methods to work with dictionaries:

MethodDescriptionExample
get()Returns the value for a keyd.get("age")
keys()Returns all keysd.keys()
values()Returns all valuesd.values()
items()Returns all key-value pairsd.items()
update()Adds or updates itemsd.update({"age": 23})
pop()Removes a specific keyd.pop("age")
popitem()Removes last inserted itemd.popitem()
clear()Removes all itemsd.clear()
copy()Copies dictionaryd.copy()
setdefault()Returns value or sets a defaultd.setdefault("city","NY")

📝 Dictionary Exercises

Try solving these exercises to strengthen your understanding:

  1. Create a dictionary of 5 countries and their capitals, then print each pair.
  2. Write a program to count the frequency of words in a sentence using a dictionary.
  3. Merge two dictionaries into one using update().
  4. Check if a given key exists in a dictionary.
  5. Create a nested dictionary for 3 students and print the details of one student.

💡 Tips & Notes

  • Always use get() instead of [] to avoid errors when a key is missing.
  • Keys must be immutable (string, number, tuple), values can be of any type.
  • Use in to check if a key exists in a dictionary.
  • Dictionaries are widely used in JSON handling and API responses.

❓ FAQs

1. Can dictionary keys be duplicated?

No, keys must be unique. If repeated, the last value overwrites the previous one.

2. Can dictionary values be duplicated?

Yes, values can be repeated, but keys cannot.

3. Are dictionaries ordered?

Since Python 3.7, dictionaries maintain insertion order. Before that, they were unordered.

4. Can I use a list as a key?

No, keys must be immutable. Lists are mutable, so they cannot be used as keys.

5. How are dictionaries different from lists?

Lists store data by index, while dictionaries store data by key. Access in dictionaries is faster when using keys.


Conclusion

 Dictionaries are one of the most powerful and flexible data structures in Python. From storing user data to working with APIs and JSON, they are used almost everywhere. By mastering dictionary operations and methods, you’ll take a huge step forward in becoming a skilled Python programmer.


📌 Related Python Tutorials



👉 Continue Learning: Explore more beginner-friendly topics and practice materials in our Programming Resource Hub.

Post a Comment

0 Comments