Reputation: 113
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)
Upvotes: 1
Views: 106
Reputation: 120391
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
DON'T USE THIS
for p in people:
names = [] #scrapedcontent
globals().setdefault(f'list_{p}', []).extend(names)
Output:
>>> list_John
[]
>>> list_James
[]
>>> list_Jane
[]
Upvotes: 2
Reputation: 596
try to do it in a dict:
for example:
d = {}
for p in people:
d[p] = []
names = ...
d[p].extend(names)
Upvotes: 0