get(): retrieves the value associated with a specified key in a dictionary

get(), takes keys and values( optional ) argument ( inputs ) .

Returns : the value of the input key , None if not found and optional parameter is not there.

The original dictionary remain same without any change.

get() with key having value

my_dict={'a':'One','b':'Two','c':'Three'}
print(my_dict.get('b'))
Output is here
Two

get() with key not present

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'}

get() with optional value for not present key

If the key is not present then we can get a fixed return value.
my_dict={'a':'One','b':'Two','c':'Three'}
print(my_dict.get('d','not found'))
Output
not found

Example 1: Accessing Nested Dictionary Safely

my_dict = {'person': {'name': 'John', 'age': 30}}
print(my_dict.get('person', {}).get('age', 'Not found'))  # Output: 30

Example 2: Using Functions for Default Values

def default_value():
    return "Default value"

my_dict = {'a': 1}
print(my_dict.get('b', default_value()))  # Output: "Default value"

Question using get()

Find out the frequency of occurrence of chars in a string?
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}

All dictionary methods
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer