Saturday, February 9, 2019

Code for Sheeba

Sheeba's Question:

I'm trying to form a dictionary that has the key as the first name and values as the list of the last names given in the list of lists. I've attached a screenshot of my problem. The input list is from line number 9 to line number 11. The required answer is from line number 21 to line number 23. I first split the names in the given list of lists into first and last names. Formed a dictionary with a list and appended the last names to it. I'm not able to attach al the last names to the list of values. My answer is on the right side of the screenshot. Please help me with this.


Solution:

source = [["David Joyner","David Tennant","David Beckham"],
          ["Ananya Birla","Ananya Agarwal","Ananya Chatterjee","Ananya Roy"],
          ["Ines Sainz","Ines Suarez","Ines Melchor"]]

def extract_names(a_list):
    dict = {}
    for lst in a_list:
        values_list = []
        name_part = lst[0].split()
        key = name_part[0]
        for name in lst:
            name_part = name.split()
            values_list.append(name_part[1])
        dict[key] = values_list
    return dict

ans = extract_names(source)
print(ans)

No comments: