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

Download source files for R Machine learning

Click here to go to source files for R Machine Learning

2 days ago

Python Machine Learning Source Files

Click here to download Python Machine Learning Source Files !

4 weeks ago

Install PyTorch on Windows

PyTorch is a deep learning package for machine learning, or deep learning in particular for…

1 month ago

Topic Modeling using Latent Dirichlet Allocation with Python

Topic modeling is a subcategory of unsupervised machine learning method, and a clustering task in…

2 months ago

Document sentiment classification using bag-of-words in Python

For online Python training registration, click here ! Sentiment classification is a type of machine…

2 months ago

Download R Course source files

Click here to download R Course source files !

11 months ago