Converting Google Analytics Reporting API V4 request results to csv with Python
Question: I'm trying to create a nicely formatted csv file with Python from a Google
Analytics Reporting API V4 request results.

The setup is using the provided example "Hello Analytics Reporting API V4."
<https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-
py#3_setup_the_sample>

The following results are as expected:  
ga:date: 20160601  
ga:sessions: 19802  
ga:pageviews: 53369  
ga:users: 17656  
ga:date: 20160602  
ga:sessions: 33718  
ga:pageviews: 71857  
ga:users: 30266  

What is needed would be something like this:  
ga:date: ga:sessions: ga:pageviews: ga:users:  
20160601 19802 53369 17656  
20160602 33718 71857 30266

I'm sure there is a straightforward solution with Python for this one.


Answer: Not sure it is very straightforward but it works.

    
    
    import sys
    from collections import OrderedDict
    
    s="""ga:date: 20160601
    ga:sessions: 19802
    ga:pageviews: 53369
    ga:users: 17656
    ga:date: 20160602
    ga:sessions: 33718
    ga:pageviews: 71857
    ga:users: 30266
    """
    
    d = OrderedDict()
    
    for l in s.splitlines():
        k,v = l.split(" ")
        if k not in d:
            d[k] = []
        d[k].append(v)
    
    nb_values = len(d[k]) # any will do
    
    sys.stdout.write(" ".join(d.keys()))
    sys.stdout.write("\n")
    
    for i in range(nb_values):
        z = [d[k][i] for k in d.keys()]
        sys.stdout.write(" ".join(z))
        sys.stdout.write("\n")
    

Result:

    
    
    ga:date: ga:sessions: ga:pageviews: ga:users:
    20160601 19802 53369 17656
    20160602 33718 71857 30266
    

