Given a list of dictionary objects, return a string

Good morning again and today we are going to solve one of the fundamental problems on Codewars.

The question goes like this, given a list of directory objects consist of the name of a person, we need to return a string which contains all those names of a person in those dictionaries within that list. The program will need to separate each person name with a comma, if there are only two persons in the list or the program has reached the last two persons on the list then the program will separate the name with an ‘&’ instead. If there is only one person on the given list then the program will just return the name of that person or if there is nobody on the list then the program will just return an empty string. Below is the program.

def namelist(names):
    
    str = ''

    if(len(names) == 0): # if no dictionary within the list
        return ''

    elif(len(names) == 1): # if only one dictionary within the list
        return names[0]['name']

    for i in range(len(names)):
        if(i == len(names)-2): # if reaches the second last dictionary
            str += names[i]['name'] + ' & '
        elif(i == len(names) - 1): # if reaches the last dictionary
            str += names[i]['name']
        else:
            str += names[i]['name'] + ', '
    
    return str

After a few runs, we get the below outcomes.

print(namelist([{'name' : 'Johnny'}, {'name' : 'Bill'}, {'name' : 'Mickey'}]))
print(namelist([{'name' : 'Johnny'}, {'name' : 'Bill'}]))
print(namelist([{'name' : 'Johnny'}]))
print(namelist([]))
outcomes for many persons, two persons, one person and no person

That is it, I will visit the above-mentioned website or other sites that are similar to that one every day to solve one or two problems to help my brain stays active!

Leave a Reply

avatar
  Subscribe  
Notify of