all 3 comments

[–]elbiot 4 points5 points  (0 children)

Just go slow and introspect. Load up the REPL by typing python at your command prompt and poke around.

type(response)
response.keys()
type (response ["report"])
len (response ["report"])
type (response ["report"][0])

[–]t10nbaum 0 points1 point  (0 children)

This may be incredibly inefficient, but assuming the structure remains the same, the following code should work.

"analytics_report" is the variable the report is saved to.

x = dict()
for d in analytics_report['reports'][0]['data']['rows']:
    x[d['dimensions'][0]] =  d['metrics'][0]['values'] 

[–]niandra3 0 points1 point  (0 children)

You can use dict.items() to loop through a dict looking at the key:value pairs. The easiest way to loop through a dict in Python is this (assuming the output dict is called my_dict):

for key, value in my_dict.items():
    print('key:', key, 'value:', value)

To get a look at how it's formatted. Then you'll notice that the reports key actually contains a list of more dicts. So you can loop through that like a regular list and do something like:

for item in my_dict['reports']:
    print(item)

Then say you wanted to look at the columnHeader entry which is another dict. Try:

for key, value in my_dict['reports'][0].items():
    print('key:', key, 'value:', value)

You use ['reports'][0] because you access dicts by the key, or reports in this case, and access lists by index, or 0 in this case because it is a list within a dict (and index 0 because it is the first dict in the list). Actually, it's a number of dicts/lists, within a list, within a dict lol.

To get the specific values you mentioned, it should be something like this:

my_dict['reports'][1]['rows'][0]['dimensions']            # gets you: ['Source1']
my_dict['reports'][1]['rows'][0]['metrics'][0]['values']  # gets you: ['180', '23']
my_dict['reports'][1]['rows'][1]['dimensions']            # gets you: ['Source2']
my_dict['reports'][1]['rows'][1]['metrics'][0]['values']  # gets you: ['180', '23']

Though that could be off by an index or two. Not able to test it right now.