Accessing Elements in Python Dictionaries
Once you get the hang of it, finding the goods inside a Python dictionary seems really simple and natural. Though you will need its key to access every value in there. They are just waiting for you. You accomplish this by popping the key within square braces [] directly behind the name of your dictionary. Here is something to check:
student = {
"name": "John",
"age": 20,
"courses": ["Math", "CompSci"]
}
print(student["name"])
Running the bit of code over will produce John. Here, "name" is your ticket; the key is "John"; the value you get in response is Slides the key "name" into those square braces, and you have the value right away.
What then occurs should you pursue a key not found in the dictionary? Well, Python has a word just for you—KeyError!
print(student["grade"])
Accessing "grade" like this results in a KeyError since it has no business in our student dictionary. Still, there's a simpler approach to manage this with the get() method. If it exists, this approach returns what is related to your key; if not, it provides you either None or a fallback value. View it:
print(student.get("name"))
print(student.get("grade"))
print(student.get("grade", "N/A"))
The first line will return: John, The second line will softly return. None as "grade" isn't there. The third line is clever; it outputs N/A since, should it not locate a "grade," we instructed it to use N/A.
Learning how to grab Python dictionary components is absolutely crucial. It prepares you for a ton of other nifty operations and techniques with dictionaries.
Modifying Elements in Python Dictionaries
Modifying a Python dictionary is quite easy. You just need to give an existing key fresh value. After the name of your dictionary, you pop that key within square braces [], hit it with an equal sign, and then add your new value. Basic, right? Like this:
student = {
"name": "John",
"age": 20,
"courses": ["Math", "CompSci"]
}
student["name"] = "Jane"
print(student)
Running such piece of code will so produce:
{
"name": "Jane",
"age": 20,
"courses": ["Math", "CompSci"]
}
Look at what occurred there? For "name," we changed the value from "John" to "Jane." And suppose what? You can slip in fresh key-value pairs the same manner. Not found in your dictionary a key? Not too concerned; just add it like this.
student["phone"] = "555-5555"
print(student)
Running it will show you:
{
"name": "Jane",
"age": 20,
"courses": ["Math", "CompSci"],
"phone": "555-5555"
}
You're right there! Your dictionary now has a brand-new item for "phone" with its number. What would happen, though, if you were to bid farewell to a key-value couple? Simply use the del keyword. With this:
del student["age"]
print(student)
And the output will be:
{
"name": "Jane",
"courses": ["Math", "CompSci"],
"phone": "555-5555"
}
We just waved farewell to "age": 20. One must first understand how to change such components in Python dictionaries. It allows you adjust things on demand, customizing your data as your program runs.
Practical Examples of Accessing and Modifying Elements in Python Dictionaries
Starting with a practical example employing a student-representing dictionary, let us This dictionary notes the student's name, age, and present course of study:
student = {
"name": "John",
"age": 20,
"courses": ["Math", "CompSci"]
}
1. Accessing Elements: Just use the key "name" provided above to obtain the student's name:
print(student["name"])
This will output: John
Modifying Elements: Assume our student decides to register for one more course. It is easily added to the "courses" list:
student["courses"].append("Physics")
print(student)
That gives us:
{
"name": "John",
"age": 20,
"courses": ["Math", "CompSci", "Physics"]
}
2. Removing Elements: Now, should the student decide to drop the "Math" course, here's how you take it off the list:
student["courses"].remove("Math")
print(student)
After running it, you’ll get:
{
"name": "John",
"age": 20,
"courses": ["CompSci", "Physics"]
}
These are only a few ways you might access and change Python dictionary items on dictionary items.