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 R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago