How can I refactor my code to return a collection of dictionaries?

110
April 03, 2022, at 07:00 AM
def read_data(service_client):
    data = list_data(domain, realm) # This returns a data frame 
    building_data = []
    building_names = {}
    all_buildings = {}
    for elem in data.iterrows():
        building = elem[1]['building_name']
        region_id = elem[1]['region_id']
        bandwith = elem[1]['bandwith']
        building_id = elem[1]['building_id']
       return {
       'Building': building,
       'Region Id': region_id,
       'Bandwith': bandwith,
       'Building Id': building_id,
       }

Basically I am able to return a single dictionary value upon a iteration here in this example. I have tried printing it as well and others.

I am trying to find a way to store multiple dictionary values on each iteration and return it, instead of just returning one.. Does anyone know any ways to achieve this?

Answer 1

You may replace your for-loop with the following to get all dictionaries in a list.

naming = {
    'building_name': 'Building',
    'region_id': 'Region Id',
    'bandwith': 'Bandwith',
    'building_id': 'Building Id',
}

return [ 
    row[list(naming.values())].to_dict() 
        for idx, row in data.rename(naming, axis=1).iterrows() 
]
Rent Charter Buses Company
READ ALSO
What could be causing install errors with pip, conda and setup.py install

What could be causing install errors with pip, conda and setup.py install

Whenever I try to install a package with pip or pip3 I get an error that starts with:

102
Snapcraft a conda environment

Snapcraft a conda environment

I have a project that uses a conda environment for dependencies managementFor now, the user can activate the environment and use it (it's exposed to the command line through an entry_point)

155
How to add bounding box coordinates to find depth from Monodepth2 model

How to add bounding box coordinates to find depth from Monodepth2 model

BACKGROUND The Monodepth2 code finds disparity map of an imageAnd from the disparity map it predicts min and max depth values

104
how to make changes to a existing column based on multiple conditions in python csv

how to make changes to a existing column based on multiple conditions in python csv

So I am working on data processing and I want to make changes to a column called "temp_coil" based on the condition in other columns

133