Python Coding Day 17 | Python Dictionaries: Structure, Adding New Items, Editing an Existing Item
Python Dictionaries: Structure, Adding New Items, Editing an Existing Item
Watch the lesson tutorial 🔻
Welcome back to the blog! Today, we are diving into one of Python's most useful data structures: Dictionaries.
If you’ve ever used a real-world dictionary to look up a word’s definition, you already understand how Python dictionaries work. They don't store data in a numbered list; instead, they use Keys to find Values.
Let’s break it down step-by-step with code.
1. The Structure: Key-Value Pairs
A dictionary is written using curly braces {}. Inside, we store data in pairs formatted as "Key": "Value".
Key: The unique identifier (like the word in a book).
Value: The data associated with that key (like the definition).
Here is how we create a dictionary and access a specific item using its key:
# Creating a dictionary called test_dic
# We use the structure {"Key": "Value"}
test_dic = {
"Bug": "An error in program",
"Function": "A piece of code"
}
# Accessing the value for the key "Bug"
print(test_dic["Bug"])
# Output:
# An error in program
Note: Unlike lists where we use index numbers (like 0 or 1), in dictionaries, we use the Key name inside the square brackets
[]to grab the data.
2. Adding New Items
Dictionaries are mutable, which means we can change them after we create them. If you want to add a new definition to your dictionary, you don't need to rewrite the whole thing.
You simply assign a value to a new key like this:
# Adding a new key "Loop" with a description
test_dic["loop"] = "It will be run over and again"
# Let's print the whole dictionary to see the change
print(test_dic)
# Output:
# {'Bug': 'An error in program', 'Function': 'A piece of code', 'loop': 'It will be run over and again'}
3. Editing an Existing Item
What happens if you made a mistake or want to update a value? You can edit an item exactly the same way you add one. Python is smart enough to know that if the Key already exists, it should just update the value instead of creating a new entry.
Here, we are changing the definition of "Bug":
# Updating the value for the existing key "Bug"
test_dic["Bug"] = "Hi Guys"
# Checking the updated dictionary
print(test_dic)
# Output:
# {'Bug': 'Hi Guys', 'Function': 'A piece of code', 'loop': 'It will be run over and again'}
Summary
Create: Use
{}withkey:valuepairs.Access: Use
dict["key"].Add/Edit: Use
dict["key"] = new_value.
Mastering dictionaries is essential for managing data in Python, especially when building real-world applications!

Comments
Post a Comment