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 To train a PyTorch Transformer for multi-track music generation, the standard paradigm is to convert…
In the field of AI and Natural Language Processing (NLP), The Transformer is the engine…
If your goal is purely symbolic melody generation (e.g., generating MIDI files or notes rather…
According to PyTorch document, In PyTorch, torch.nn.functional.affine_grid generates a 2D or 3D flow field (sampling…
Creating an Android mobile app with a deep learning AI model involves several key steps:…
Click here to go to source files for R Machine Learning