I found this question (and related links) useful, so thought I would respond here even though the original query is now quite old.
I found the code you have adapted quite hard to follow. Mainly because of my lack of Python experience but partly because of the additional checks (number of selected objects > 0 and create new collection if one doesn't already exist).
This version is less sophisticated, but is perhaps easier to follow and it resolves the  related error.
#create list of collection names
CollList = ['Structure', 'Architecture', 'Biscuits']
#Find length of collection list (could just use '3' in this case, but I prefer to have a general case)
CollLen = len(CollList)
#create collections from the list
for x in range(0,CollLen):
y = bpy.data.collections.new(CollList[x])
#create list of all selected mesh objects
ListObjects = [ x for x in bpy.context.selected_objects if x.type == 'MESH' ]
#run through list and move objects
for z in ListObjects: