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

Fine tuning a Hugging Face transformer model for multi-track music generation

To train a PyTorch Transformer for multi-track music generation, the standard paradigm is to convert…

3 weeks ago

what are Transformer, LLM , and GPT

In the field of AI and Natural Language Processing (NLP), The Transformer is the engine…

3 weeks ago

Main framework for PyTorch music generation model

If your goal is purely symbolic melody generation (e.g., generating MIDI files or notes rather…

4 weeks ago

affine_grid() in pytorch

According to PyTorch document, In PyTorch, torch.nn.functional.affine_grid generates a 2D or 3D flow field (sampling…

3 months ago

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:…

12 months ago

Download source files for R Machine learning

Click here to go to source files for R Machine Learning

1 year ago