Understanding How dict.get(key) Differs from dict[key]
The difference between dict.get(key)
and dict[key]
lies primarily in how they handle missing keys.
Using
dict.get(key)
:Returns the value associated with the specified key.
If the key is not found, returns
None
by default (or a specified default value).Does not raise a
KeyError
.
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Accessing an existing key
print(my_dict.get('a')) # Output: 1
# Accessing a missing key
print(my_dict.get('x')) # Output: None
# Accessing a missing key with a default value
print(my_dict.get('x', 'Key not found')) # Output: Key not found
Using
dict[key]
:Also returns the value associated with the specified key.
If the key is not found, raises a
KeyError
.
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Accessing an existing key
print(my_dict['a']) # Output: 1
# Accessing a missing key
# This will raise a KeyError: 'x'
# print(my_dict['x'])
# Using try-except to handle missing key
try:
print(my_dict['x'])
except KeyError:
print('Key not found')
So, the primary difference is in how they handle missing keys: dict.get(key)
returns None
or a default value if the key is missing, while dict[key]
raises a KeyError
if the key is not found.