0

I'm using Wikipedia's Pageviews API in Python and I'm trying to get time and views for a list of pages. My idea was to create a dictionary with the wikipedia page (eg. Rome) as key and all the attributes as a dict of values. Then I want to create a dict with the wikipedia page name as the name of the dict and for the key the time and for the value the views. I can't create one dynamically, however.

My code is:

dfs = []

import pageviewapi
emptylist = []


dictrome = {}
dictparis = {}
dct0 = {}

list = ['Paris', 'Rome']
for x in list:
    dct0[x] = pageviewapi.per_article('it.wikipedia', x, '20150101', '20210101',
                        access='all-access', agent='all-agents', granularity='monthly')
    if 'Rome' in dct0:
        for i in dct0.values():
            for p in range(0,len(i['items'])):
                dictrome[(i['items'][p]['timestamp'])] = (i['items'][p]['views'])
    else:
        for i in dct0.values():
            for p in range(0,len(i['items'])):
                dictparis[(i['items'][p]['timestamp'])] = (i['items'][p]['views'])

And the output I want, which is the one I have, is:

dictrome: {'2015070100': 890, '2015080100': 879, '2015090100': 971, '2015100100': 1097, '2015110100': 2259}
dictparis : {'2015070100': 482, '2015080100': 467, '2015090100': 371, '2015100100': 425, '2015110100': 408}

I just want to automate that "if" condition, because the pages in my list will be hundreds.

1 Answers1

0

Let me first address the variable name list. Thing is, list is a build-in function to create lists. You are reassigning it, which should not be done in any circumstance.

So now to your problem. I don't know, why you wouldn't just use a result dictionary with the city as the key, like:

result[<city>]=result_dict

Anyways, you can accomplish what you want by using the globals() function, which returns a global symboltable as a dict. I don't recommend this but here is an example:

for i in range(0,number):
    globals()[f"var_{i}"]=i # or dict() in your case.
Cano707
  • 181
  • 1
  • 10
  • I could also use a result dictionary but how do I insert the variable city name? – WikiTrial99 Jan 19 '22 at 18:06
  • You just generate the results as you did so far, but instead of storing it in `dictrome` for example you can do 'result[x] = result_dict' since x is the name of the city in the list you iterate over. Just define the `result_dict` instead of `dictrome`, `dictparis`, etc. Hope this gives you an idea. – Cano707 Jan 19 '22 at 18:15
  • I would overwrite result_dict every time right? – WikiTrial99 Jan 19 '22 at 18:23
  • like what exactly is result[x]? should I instantiate it how? – WikiTrial99 Jan 19 '22 at 18:25