'Create multiple activities in Brightway2 with for loop

I'm trying to create multiple electricity mix activities in Brightway2 for different countries. Since I don't want to write the same code for each activity every time just with a different location I'm currently trying to solve this by iterating over the list with the country names with a for loop and inserting that into the location and name of the activity. However it does not seem to work and I don't understand the error.

for country in AnnualProductionMix['`countries']:
countriesPM = eidb.new_activity(code = str(country) + 'PM2020', name = "Electricity, Production Mix" + str(country), unit = "kWh", location = str(country))
countriesPM.save()

And this is the Error that I get: IntegrityError: UNIQUE constraint failed: activitydataset.database, activitydataset.code

When I just print the activities it works, it just doesn't when I try to save them to the database. I guess the problem is that they are all assigned to countriesPM but I can't make a dynamic variable name here it gives me another different error.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source