There is a list consisting of the following lists:

['Member Profile Mostafa', 'site1 / 1', 'Website', 'site2', 'Twitter', 'sdfsdf', 'WeChat'] ['Member Profile Dinesh', 'site1 / 2', 'Twitter ',' 45fghfgh ',' Birthday ',' October 28 '] [' Roman Profile ',' site1 / 3 ',' Twitter ',' drgedrg ',' Birthday ',' February 9 ']

Items with even indices in nested lists are column headings. You need to save the data in a CSV in this form:

Member profile Website Twitter WeChat Birthday site1 / 3 site2 sdfsdf empty empty site1 / 2 empty 45fghfgh empty October 28 site1 / 3 empty drgedrg empty February 9

That is, we read the table headers by searching them in lists. After that we form the table. It contains user information on each line.

How to do it?

  • But these lists - this is the original data, or you parsili them from somewhere? But it may be easier to pereparsit in a normal way? Because this form is a bunch of garbage, not the original data. - Xander

1 answer 1

In general, something like this can be done:

data = [ ['Профиль участника Mostafa', 'site1/1', 'Веб-сайт', 'site2', 'Twitter', 'sdfsdf', 'WeChat'], ['Профиль участника Dinesh', 'site1/2', 'Twitter', '45fghfgh', 'День рождения', '28 октября'], ['Профиль участника Roman', 'site1/3', 'Twitter', 'drgedrg', 'День рождения', '9 февраля'] ] rows = [] for line in data: item = { 'Профиль участника': line[1], } for n in range(2, len(line)-1, 2): item[line[n]] = line[n+1] rows.append(item) import csv keys = ['Профиль участника', 'Веб-сайт', 'Twitter', 'WeChat', 'День рождения'] with open('result.csv', 'w') as output_file: dict_writer = csv.DictWriter(output_file, keys) dict_writer.writeheader() dict_writer.writerows(rows) 
  • Thank you. works. Only added a line: dict_writer = csv.DictWriter (output_file, keys, delimiter = ';') - added the separator ";" so that everything is written not in one column, but in different ones. - Vladimir