Dictionary is a data structure type in Python. One reason for why Python is so popular among programmers is that dictionary provides an useful and effective way to store key-value pairs information. When functions in Python carry out some tasks, it can return required information to a dictionary.
In the following example, we define a function which aims to store passing information into an dictionary object and return it.
#define a function for storing personal information
#to a dictionary
def person(first, last):
"""store information of a person."""
ps = {'first': first, 'last': last}
return ps
#create an instance of person class, passing information
wz = person('Wilson', 'Zhang')
print(wz)
#output
{'first': 'Wilson', 'last': 'Zhang'}
When some information about a person is optional when calling the function, we can add an optional argument to the function as well. The following example shows that information about age is set as optional with default value as empty.
#define a function for storing personal information
#to a dictionary
def person(first, last, age=''):
"""store information of a person."""
ps = {'first': first, 'last': last}
if age:
ps['age'] = age
return ps
#create an instance of person class, passing information
ws = person('Wilson', 'Zhang', age=32)
print(ws)
You can also watch video on Python full tutorial from our YouTube channel.
Click here to download Python Course Source Files !
For online Python training registration, click here ! Pandas provides flexible ways of generating data…
For online Python training registration, click here ! Data frame is the tabular data object…
Click her for course registration ! When a data frame in Python is created via…
We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…