Understanding Python Dictionaries
Subhash Kumar Yadav
Aspiring Web Developer | Python | HTML | CSS | BCA Graduate
Have you ever thought about how your computer knows where to find your favorite game or how your phone stores your contacts?
One of the coolest and most useful data structures in Python is the dictionary.
Imagine having a magical notebook where you can look up any information instantly. That's what a Python dictionary is like!
What is a Python Dictionary ?
A Python dictionary is a collection of key-value pairs.
Think of it as a real-life dictionary, where you look up a word (the key) to find its meaning (the value).
Unlike a real dictionary, though, a Python dictionary can hold any kind of information : numbers, strings, lists, even other dictionaries!
Creating a Dictionary
Creating a dictionary in Python is simple.
Here's how you do it :
# Creating an empty dictionary
my_dict = {}
# Creating a dictionary with some key-value pairs
student_info = {
"name": "Sky",
"age": 14,
"grade": "8th"
}
In the "student_info" dictionary, "name", "age", and "grade" are the keys, and "Sky", 14, and "8th" are their respective values.
Accessing Values
To get the value associated with a key, you use square brackets:
print(student_info["name"])
print(student_info["age"])
Output :
Sky
14
If you try to access a key that doesn’t exist, you’ll get an error. To avoid this, you can use the get method, which returns None (or a default value) if the key isn’t found:
print(student_info.get("hobby", "Not specified"))
Output :
Not specified
Adding and Updating Values
Adding a new key-value pair is easy. Just use a new key and assign it a value:
student_info["hobby"] = "painting"
print(student_info)
Output :
{'name': 'Sky', 'age': 14, 'grade': '8th', 'hobby': 'painting'}
You can also update the value of an existing key:
student_info["grade"] = "9th"
print(student_info)
Output :
{'name': 'Sky', 'age': 14, 'grade': '9th', 'hobby': 'painting'}
领英推荐
Removing Items
You can remove a key-value pair using the del keyword or the pop method:
del student_info["hobby"]
print(student_info)
grade = student_info.pop("grade")
print(student_info)
print(grade)
Output :
{'name': 'Sky', 'age': 14, 'grade': '9th'}
{'name': 'Sky', 'age': 14}
9th
Looping Through a Dictionary
To loop through a dictionary, you can use a for loop. You can loop through the keys, the values, or both:
# Looping through keys
for key in student_info:
print(key)
# Looping through values
for value in student_info.values():
print(value)
# Looping through key-value pairs
for key, value in student_info.items():
print(f"{key}: {value}")
Examples of Python Dictionaries in Action
Example 1 : Contact List
Imagine you want to store contact information for your friends:
contacts = {
"John": "123-456-7890",
"Jane": "987-654-3210",
"Bob": "555-555-5555"
}
# Accessing a contact number
print(contacts["Jane"])
Output:
987-654-3210
Example 2 : Shopping Cart
A shopping cart can be represented as a dictionary, where the keys are the item names and the values are their prices:
shopping_cart = {
"apple": 0.5,
"banana": 0.3,
"milk": 1.5
}
# Calculating the total cost
total_cost = sum(shopping_cart.values())
print(f"Total cost: ${total_cost}")
Output:
Total cost: $2.3
Example 3 : Student Grades
You can store students' grades in a dictionary:
grades = {
"Sky": "A",
"Bob": "B",
"Charlie": "C"
}
# Printing each student's grade
for student, grade in grades.items():
print(f"{student}: {grade}")
Now that you know the basics of Python dictionaries, it's time to start experimenting. Try creating your own dictionaries and see how they can make managing data easier and more fun.
Whether you're storing contact info, shopping lists, or anything else, dictionaries are a powerful tool to have in your Python toolkit.
Remember, this isn't a guide or tutorial—I'm just sharing what I've learned.
If you found this interesting and want more insights into Python or have any questions, feel free to like and comment below.
Let's connect and learn more about Python together!
Happy coding!
Student at Bangalore North University
2 个月Very informative