Accessing Values
Using square brackets
To get a value, write the dictionary name followed by the key in square brackets:
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print(person["age"]) # Output: 30
print(person["name"]) # Output: AliceUsing get()
The get() method does the same thing, but lets you provide a fallback value if the key doesn’t exist:
print(person.get("age")) # Output: 30
print(person.get("occupation", "Not specified")) # Output: Not specifiedIf you use square brackets with a key that doesn’t exist, Python raises an error. get() returns None (or your fallback) instead — which is safer when you’re not sure if a key is there.
Use get() when a key might not be in the dictionary. Use square brackets when you’re sure the key exists and want Python to raise an error if it doesn’t.
Try it out
main.py
Output
Last updated on