Python

Returning a dictionary with functions in Python

We provide effective and economically affordable training courses for R and Python, Click here for more details and course registration !

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.

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