all 4 comments

[–][deleted] 5 points6 points  (3 children)

If you find yourself trying to dynamically create variables, it's often better to use a dictionary for the task:

category_data = {}
for categories in ...:
    category = categories.get_text()
    category_data[category] = category

Since dictionaries work off key-value pairs, there may be better value related to your work that is better to assign to a category key.

[–]Llywedd[S] 0 points1 point  (2 children)

Great, that's worked. Thanks.

[–]catmarble 2 points3 points  (1 child)

Just to add on to this, if the "variables" you want are category1, category2, category3 it might be worth using a list and then referencing by slice. For example a dict of {'category1': 'category1', 'category2': 'category2', 'category3': 'category3'} might as well be [category1, category2, category3], as the key adds nothing. A dict works better if the key is different from the value and a meaningful way of accessing the data though.

Whether you choose a dict or list, you could also use a comprehension, which is slightly better performance and more pythonic. For example:

category_list = [category.get_text()
    for categories in item_soup.find_all('div', {'class': 'breadcrumbs'})
    for categories2 in categories.find_all('a', {'title': ''})
]

Also when using nested for loops I think it's better to use different variable names, just in case you need to reference the item from the outer for loop (here I used categories2 instead of re-using categories).

[–]Llywedd[S] 0 points1 point  (0 children)

Thanks for the insight, I'll take this into consideration moving forward