DEV Community

samueldavidwinter
samueldavidwinter

Posted on

Extracting a list of tuples from a list of dictionaries, some values separated with commas and single quotes and some without

I have a list of dictionaries, each dictionary contains:

First name
Middle name
Last name
Title
Address
Email address
Loyalty program For one client. Some of this information may be missing
segment = [{'first-name': 'Elsa', 'last-name': 'Frost', 'title': 'Princess', 'address': '33 Castle Street, London', 'loyalty-program': 'Gold'}, {'first-name': 'Anna', 'last-name': 'Frost', 'title': 'Princess', 'loyalty-program': 'Platinum'}, {'first-name': 'Harry', 'middle-name': 'Harold', 'last-name': 'Hare', 'title': 'Mr', 'email-address': 'harry.harold@hare.name', 'loyalty-program': 'Silver'}]
For clients who have a physical address, I need to extract a list of tuples. Each tuple represents one client and contains their title, first name, middle name, and last name in that order if defined, and the mailing address.

My code appears to be working.

However, within each tuple, there needs to be single quotation marks around the whole and not individual parts of a clients name. There also needs to be quotation marks around the address. A comma needs to separate the address and the full name.

('Princess Elsa Frost', '33 Castle Street, London')
My code is returning the right information, but the elements of a patients name are separated by commas and single quotation marks

def process_clients(segment):

#Creating a list to contain tuples with client full name and mailing address. 
updated = []
#Interacting through each dictionary, which represents each client
for dic in segment:
    newclient=[]
#Adding clients with a mailing address
    try:
        add = dic["address"]
    except:
        continue
#Adding, in order, the "title", "first-name", "middle-name", "last-name" and "address" of each client
    for data in ["title", "first-name", "middle-name", "last-name", "address"]:
        try:
            value = dic[data]
            newclient.append(value)
#If "title", "first-name", "middle-name" or "last-name" is not present in a clients data, no action is taken
        except:
            pass
#Additing the tuples with extracted client data to the created list        
    updated.append(tuple(newclient))
return updated

process_clients(segment)

[('Princess',' Elsa ',' Frost ', '33 Castle Street, London')]

Top comments (0)