Wednesday, May 27, 2020

IslandT: Return people from a list and dictionary with Python

In this article, we are going to return a list of names that show whether that person is nice or naughty based on True (Nice) or False (Naughty) value from the ‘was_nice’ key within a list of dictionaries pass into either the get_nice_names function which will only return the name of a person who is nice or get_naughty_names function which will do vise versa.

A list of dictionaries will get passed into below functions that will return either a list of nice person names or a list of naughty person names.

def get_nice_names(people):

    nice_name_list = []
    for nice_list in people:
        if nice_list["was_nice"] == True:
            nice_name_list.append(nice_list["name"])
    return nice_name_list

def get_naughty_names(people):

    bad_name_list = []
    for bad_list in people:
        if bad_list["was_nice"] == False:
            bad_name_list.append(bad_list["name"])
    return bad_name_list

So if you pass in a list of dictionaries into the nice person function you will receive a list of nice person names (was_nice == True) in return. For example,

nice = [{'name': 'Santa', 'was_nice': True}, {'name': 'Warrior reading this kata', 'was_nice': True}] # ['Santa', 'Warrior reading this kata']

Leave your comment below this post if you have another solution to the above problem.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...