Python dictionary

Using get() method in Python to return value of the key in dictionary

We provide effective and economically affordable online training courses for R and Python, click here for more details and course registration !

Python’s dictionary object type provides a function get() to return the value of the key in a dictionary. The difference between get() method and using bracket to index the key is that get() will return NULL in result when the key is not present, while the latter raises an error for nonexistent key. Following code example shows using get() with default value for the key in a dictionary.

#create a dictionary
d = {'Wilson': 32, 'Dudu': 20, 'Maomao': 22}
#return value of 'Wilson'
print(d.get('Wilson'))
#output, since value is present, it works
32
#alternative way using brackets
print(d['Wilson'])
#output, since value is present, it works
32
#if we use brackets for a nonexistent key, error comes
print(d['Mia'])
#output
KeyError: 'Mia'
#Python get() Method with default parameter.
print(d.get('Mia', "Not found"))
#output
Not found

get() methods applies for nested dictionary too.

## using nested get()
test_dict = {'Wilson': {'Age': 32, 'Gender': 'male'},  'Dudu': {'Age': 20, 'Gender': 'male'}, 'Maomao': {'Age': 22, 'Gender': 'male'}}
res = test_dict.get('Wilson', {}).get('Age')
res

For getting more knowledge of Python and a preview of our training course, you can watch Python tutorial videos on our YouTube channel !

wilsonzhang746

Recent Posts

Fine tuning a Hugging Face transformer model for multi-track music generation

To train a PyTorch Transformer for multi-track music generation, the standard paradigm is to convert…

3 weeks ago

what are Transformer, LLM , and GPT

In the field of AI and Natural Language Processing (NLP), The Transformer is the engine…

3 weeks ago

Main framework for PyTorch music generation model

If your goal is purely symbolic melody generation (e.g., generating MIDI files or notes rather…

4 weeks ago

affine_grid() in pytorch

According to PyTorch document, In PyTorch, torch.nn.functional.affine_grid generates a 2D or 3D flow field (sampling…

3 months ago

How to create an Android mobile app with a deep learning AI model ?

Creating an Android mobile app with a deep learning AI model involves several key steps:…

12 months ago

Download source files for R Machine learning

Click here to go to source files for R Machine Learning

1 year ago