1

There are multiple dimensions and metrics that I want to pull from Google Analytics via their API, and this requires dimension:metric(s) pairing. Naturally, I thought dictionary might be a good option for this. To minimize typing, and increase readability, this is what I tried.

dim_dict = {
    0:'',
    1:'ga:searchUsed',
    2:'ga:searchKeyword',
    3:'ga:pageTitle',
    4:'ga:operatingSystem',
    5:'ga:goalPreviousStep3'
    }

metric_dict = {
    1:'ga:sessions',
    2:'ga:sessionDuration',
    3:'bounceRate',
    4:'pageviews',
    5:'ga:searchSessions',
    6:'ga:goalCompletionsAll'
    }

dim_metric_dict = {
    0:[1,2,3,4,5,6],
    1:[1,2,3,4,5,6],
    2:[1,2,3,4,5,6],
    3:[1,2,3,4,5,6],
    4:[1,2,3,4,5,6],
    5:[6]
    }

query_dict = {}
for dim_key in dim_dict.keys():
    met = []
    for metric_key in dim_metric_dict[dim_key]:
        met.append(metric_dict[metric_key])
    query_dict.update({dim_dict[dim_key]:met})

Then, I'm using the following code to make API requests:

def get_ga_kpi(start_date, end_date, dimensions='', sort='ga:pageviews'):
    service = build('analytics', 'v3', http=http)
    metrics = query_dict[dimensions]
    if sort not in metrics:
        sort = metrics[0]
    data_query = service.data().ga().get(**{
        'ids': 'ga:#######',
        'metrics': '%s' % (','.join(metrics)),
        'dimensions': '%s' % (dimensions),
        'start_date':'%s' % (start_date),
        'end_date':'%s' % (end_date),
        'sort': '-%s' % (sort)
        })
    return feed['rows']

The code works as intended, but I'm wondering if there is a better way to approach this problem. Thanks for any input!

8
  • from what i see, it's the best approach - otherwise you can try parsing a YAML with the specs Commented May 9, 2014 at 21:13
  • 1
    It may be a case you want to extract these out into data files - that's a lot of data to be embedded into the source. Commented May 9, 2014 at 21:13
  • @Lattyware, could you elaborate what you mean by "the source", and what would data files look like? I'm still learning the lingos :) Commented May 9, 2014 at 21:16
  • I think he just means "the source code." Namely, your main program versus a separate file to store string data in. Commented May 9, 2014 at 21:17
  • @user3499545: ah I see... maybe I don't understand this correctly, but do you mean that I would store the dictionaries in a separate .py file? or utilize something like .txt as dimension-metric pairing Commented May 9, 2014 at 21:19

1 Answer 1

1

I don't know if this is much better, but you could use a dictionary comprehension and enumerate to avoid typing out all of the numbers.

For example, the dim_dict construction could become:

    dim_list = ['','ga:searchUsed','ga:searchKeyword','ga:pageTitle','ga:operatingSystem','ga:goalPreviousStep3']
    dim_dict = {key:value for (key,value) in enumerate(dim_list)}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.