0

I have a function that should read the file and convert it to a list with dictionaries and then make it return the full list, but it only returns the first line, unless I print it, then it gives the full list.

And I don't know how to make the dictionary in a different/ better way, because now it's not DRY (I think)

def create_launch_data(filename):

with open(filename, "r") as f:
    for line in f:
        list_txt = line.splitlines()
        for i in list_txt:
            list_item = i.split(",")

            dictionary = {
            "launch_succes": list_item[0],
            "launch_site": list_item[1],
            "mission_name": list_item[2],
            "launch_year": list_item[3],
            "rocket": list_item[4],
            "video_link": list_item[5],
            "launch_date": list_item[6],
            "ship_name": list_item[7]
            }


        launch_data = list(dictionary.values())
        print(launch_data)

create_launch_data("spacex_data.txt")

txt:

True,Cape Canaveral Air Force Station Space Launch Complex 40,Thaicom 6,2014,Falcon 9,https://www.youtube.com/watch?v=AnSNRzMEmCU,2014-01-06T14:06:00-04:00,None
True,Cape Canaveral Air Force Station Space Launch Complex 40,AsiaSat 6,2014,Falcon 9,https://www.youtube.com/watch?v=39ninsyTRk8,2014-09-07T01:00:00-04:00,None
True,Cape Canaveral Air Force Station Space Launch Complex 40,OG-2 Mission 2,2015,Falcon 9,https://www.youtube.com/watch?v=O5bTbVbe4e4,2015-12-22T21:29:00-04:00,None
True,Cape Canaveral Air Force Station Space Launch Complex 40,CRS-1,2012,Falcon 9,https://www.youtube.com/watch?v=-Vk3hiV_zXU,2012-10-08T20:35:00-04:00,American Islander
True,Vandenberg Air Force Base Space Launch Complex 4E,CASSIOPE,2013,Falcon 9,https://www.youtube.com/watch?v=uFefasS6bhc,2013-09-29T09:00:00-07:00,American Spirit
SmugSnail
  • 39
  • 5
  • 1
    Use the `csv` module. See https://stackoverflow.com/questions/21572175/convert-csv-file-to-list-of-dictionaries – Stuart Sep 26 '22 at 00:41
  • `list_item` is already a list of values that you want, and you can easily make a list of the corresponding keys in the same order; see the second linked duplicate to get from there to the dict you want. See the first linked duplicate to understand how to assemble the results from looping. – Karl Knechtel Sep 26 '22 at 00:42
  • Assuming that your data is in that format, it is a CSV file, yes, which should be handled using the standard library, yes. I will add @Stuart's link as a third duplicate. – Karl Knechtel Sep 26 '22 at 00:45

0 Answers0