[英]Python: Is there a better way to construct a dictionary?
There are multiple dimensions and metrics that I want to pull from Google Analytics via their API, and this requires dimension:metric(s) pairing. 我想通过其API从Google Analytics(分析)中提取多个维度和指标,这需要对维度:指标进行配对。 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: 然后,我使用以下代码提出API请求:
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!
感谢您的输入!
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_dict构造可能变为:
dim_list = ['','ga:searchUsed','ga:searchKeyword','ga:pageTitle','ga:operatingSystem','ga:goalPreviousStep3']
dim_dict = {key:value for (key,value) in enumerate(dim_list)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.