How to Use Dictionary get() Method in PythonPython Basics


The get() function returns the value of the given key if the key is in the dictionary, otherwise, it returns the default value.

Example

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

dict1 = {'Name': 'Gerryzhang', 'Age': 24,'sex':'man','ID':'2019'}

print(dict1.get('Name'))
print(dict1.get('Age'))
print(dict1.get('sex'))
print(dict1.get('ID'))

Output:

Gerryzhang
24
man
2019

Syntax

dict.get(key[, value])

Parameters

Name Description
key The key to be searched in the dictionary.
value The value to be returned if the key is not found. The default value of the key is None.

Return Value

It returns the value of the specified key if the key is found in the dictionary, otherwise the default value.

© 2024 Cheerlearn.com, all rights reserved. Privacy Policy | Contact Us