I've been working on a webpage scraper and I would like to create separate lists containing different elements. There would have to be more than a 1000 lists and I am trying to run that through a for loop. I need the lists to be appropriately named according to the element in each particular iteration. I tried using globals() to achieve this but it only takes an int or a char and not a string. Is there a way to achieve this?
For an example:
If people = ['John', 'James', 'Jane']
I need 3 lists named
Johnlist=[]
Jameslist=[]
Janelist=[]
Below is what I tried but it returns an error asking for either an int or a char.
for p in people:
names = #scrapedcontent
globals()['%list' % p] = []
for n in names:
globals()['%list' % p].append(#scrapedcontent)
CodePudding user response:
I strongly discourages you to use globals
, locals
or vars
As suggested by @roganjosh, prefer to use dict:
from collections import defaultdict
people = defaultdict(list):
for p in people:
for n in names:
people[p].append(n)
Or
people = {}
for p in people:
names = #scrapedcontent
people[p] = names
CodePudding user response:
try to do it in a dict:
for example:
d = {}
for p in people:
d[p] = []
names = ...
d[p].extend(names)