简体   繁体   中英

Python, use a list of dictionaries returned from a function

I am trying to return the list of dictionaries and then use it outside the function:

 def myfunc():
     fileName: some file on my system
     with open(fileName) as csv1:
         dataDict = csv.DictReader(csv1, delimiter=',')

         return dataDict    

But when I call t function, I get the error "ValueError: I/O operation on closed file."

myDict = myfunc()

for row in myDict:
    print(row)

How should I declare and use a list of dictionaries? Once the dictionary is returned, I need to also access its fieldnames. Any tips or help is greatly appreciated.

You could copy it into another variable and return that...

 def myfunc():
     fileName: some file on my system
     mydict = {}
     with open(fileName) as f: 
         for row in csv.DictReader(f, delimiter=','):
             mydict[row['first_column']] = row['second_column'] + row['third_column']

     return mydict  

replace the column names with those in the csv.

DictReader is lazy. Actually turn it into a list and return that, so that the file is read while it's still open.

def myfunc():
     fileName: some file on my system
     with open(fileName) as csv:
         return list(csv.DictReader(csv, delimiter=','))

The with statement automatically closes the file. When you try to access data through the DictReader outside of the with statement, the DictReader is unable to access the closed file, and so you get the IOError.

You can get around this by gathering the rows from the file into a list before returning from the function:

 def myfunc():
     fileName: some file on my system
     with open(fileName) as csv1:
         dataDict = csv.DictReader(csv1, delimiter=',')
         list_of_dicts = list(datadict)
         return list_of_dicts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM