Thursday, November 3, 2011

Python dictionary get() method

Description:
This method returns a value for the given key. If key is not available, then returns the default value.

Syntax:
dict.get(key, default=None)
Parameters:
key: Key to be searched in the dictionary.
default: Value to be returned if key does not exist.

Example:
dict = {'Name': 'Vera', 'Age': 10, 'Sex': None}
print dict.get('Age')
print dict.get('Position', "Student")
print dict.get('Sex','Male')

Following results are returned:
10
Student
None

No comments:

Post a Comment