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

How to create an Android mobile app with a deep learning AI model ?

Creating an Android mobile app with a deep learning AI model involves several key steps:…

2 weeks ago

Download source files for R Machine learning

Click here to go to source files for R Machine Learning

2 months ago

Python Machine Learning Source Files

Click here to download Python Machine Learning Source Files !

2 months ago

Install PyTorch on Windows

PyTorch is a deep learning package for machine learning, or deep learning in particular for…

3 months ago

Topic Modeling using Latent Dirichlet Allocation with Python

Topic modeling is a subcategory of unsupervised machine learning method, and a clustering task in…

3 months ago

Document sentiment classification using bag-of-words in Python

For online Python training registration, click here ! Sentiment classification is a type of machine…

4 months ago