cross-tabulation pointers

John Hunter jdhunter at ace.bsd.uchicago.edu
Wed Jun 16 13:48:39 CEST 2004


>>>>> "selwyn" == selwyn  <selwyn at aotearoa.is.home.nz> writes:

    selwyn> hi there, I would like some pointers on a pythonesque way
    selwyn> of cross-tabulating an SQL result set.

Supposing your results are a row of dicts

results = (
    {'dept' : 'hr',    'gender' : 'm'},
    {'dept' : 'hr',    'gender' : 'f'},
    {'dept' : 'sales', 'gender' : 'm'},
    {'dept' : 'sales', 'gender' : 'm'},    
    )

count = {}
for row in results:
   dept = row['dept']
   if row['gender']=='m': ind = 0
   else: ind = 1
   count.setdefault(dept, [0,0])[ind] += 1

print count




More information about the Python-list mailing list