user13407738
user13407738

Reputation: 23

How to create a list with list comprehension and generators

i'm retrieving some data from the active directory with pyad library. Once i execute a query, I would like to create a dataframe with the data retrieved:

import pyad
import pyad.adquery as query

pyad.set_defaults(ldap_server=xxxxxx)
q = query.ADQuery()
q.execute(
    attributes=[attribute1,attribute2,attribute3]
    where_clause=xxx
    base_dn=xxxxx
)

Once i run the query, i'm creating a dataframe in this way:

parameter1 = []
parameter2 = []
parameter3 = []

for x in q.get_results(): #IT'S A GENERATOR
    parameter1.append(x['attribute1'])
    parameter2.append(x['attribute2'])
    parameter3.append(x['attribute3'])

df = pd.Dataframe({'P1':parameter1, 'P2':parameter2, 'P3':parameter3})

The way i'm creating the dataframe is not clean and elegant, is there a way to improve this code? If it would be just one parameter i would do:

df = pd.Dataframe({'P1': [x['parameter1'] for x in q.get_results()]})

but q is a generator so i can't run three list comprehensions without running again the method q.execute(...)

Upvotes: 0

Views: 81

Answers (1)

rdas
rdas

Reputation: 21275

Get the generator out of the way

results = list(q.get_results())

Then you should be able to:

df = pd.Dataframe({'P1': [x['parameter1'] for x in results], 'P2': [x['parameter2'] for x in results], ...})

Upvotes: 2

Related Questions