Search code examples
pythonparameter-passingkeyword-argument

Iterate over list of dictionaries. Pass into function


Disclaimer. I am new to python and trying to learn. I have a list of dictionaries containing address information I would like to iterate over and then pass into a function as arguments.

print(data)

[{'firstName': 'John', 'lastName': 'Smith', 'address': '123 Lane', 'country': 'United States', 'state': 'TX', 'city': 'Springfield', 'zip': '12345'}, {'firstName': 'Mary', 'lastName': 'Smith', 'address': '321 Lanet', 'country': 'United States', 'state': 'Washington', 'city': 'Springfield', 'zip': '54321'}]

I iterate over the list and attempt pass in the values, but the values are past as a list instead of individually. I'm not sure how to correct. I'm still grasping arguments and keyword arguments. Any help and guidance is appreciated.

from usps import USPSApi, Address

input_name = [li['lastName'] for li in data]
input_address = [li['address'] for li in data]
input_city = [li['city'] for li in data]        
input_state = [li['state'] for li in data]        
input_zip = [li['zip'] for li in data]        
input_country = [li['country'] for li in data]  

address = Address(
    name = input_name,
    address_1= input_address,
    city= input_city,
    state=input_state,
    zipcode=input_zip
)
usps = USPSApi('------', test=True)
validation = usps.validate_address(address)
data_results = validation.result 
print(data_results)

Solution

  • You already have all the logic to process a single data point, just expand it to multiple data points as shown below using a loop.

    from usps import USPSApi, Address
    
    for item in data:
        kwargs = dict()
    
        kwargs['name'] = item['lastName']
        kwargs['address_1'] = item['address']
        kwargs['city'] = item['city']
        kwargs['state'] = item['state']
        kwargs['zipcode'] = item['zip']
    
        address = Address(**kwargs)
    
        usps = USPSApi('------', test=True)
        validation = usps.validate_address(address)
        data_results = validation.result 
        print(data_results)
    

    Without syntactic sugar it becomes

    for item in data:
        kwargs = dict()
    
        name = item['lastName']
        address_ = item['address']
        city = item['city']
        state = item['state']
        zip_ = item['zip']
    
        address = Address(
            name=name,
            address_1=address_,
            city=city,
            state=state,
            zipcode=zip_)