value = my_dict.get(key, default) returns the value for a key without raising KeyError when the key is missing. If no default is supplied, the missing-key result is None.
See the complete Dictionary Methods table for the other dictionary operations in this cluster.
my_dict={'a':'One','b':'Two','c':'Three'}
print(my_dict.get('b'))
Output is here
Two
my_dict={'a':'One','b':'Two','c':'Three'}
print(my_dict.get('d'))
print(my_dict)
Output ( there is no change in dictionary )
None
{'a': 'One', 'b': 'Two', 'c': 'Three'}
my_dict={'a':'One','b':'Two','c':'Three'}
print(my_dict.get('d','not found'))
Output
not found
my_dict = {'person': {'name': 'John', 'age': 30}}
print(my_dict.get('person', {}).get('age', 'Not found')) # Output: 30
The default expression is evaluated before get() is called. Use this form when that eager evaluation is acceptable.
def default_value():
return "Default value"
my_dict = {'a': 1}
print(my_dict.get('b', default_value())) # Output: "Default value"
my_str='Welcome to Python'
my_dict={}
for i in my_str:
my_dict[i]=my_dict.get(i,0)+1
print(my_dict)
Output
{'W': 1, 'e': 2, 'l': 1, 'c': 1, 'o': 3, 'm': 1, ' ': 2,
't': 2, 'P': 1, 'y': 1, 'h': 1, 'n': 1}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.