简体   繁体   English

Python,使用从 function 返回的字典列表

[英]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:我正在尝试返回字典列表,然后在 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."但是当我调用 t function 时,我收到错误“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.将列名替换为 csv 中的列名。

DictReader is lazy. DictReader 很懒惰。 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. with语句自动关闭文件。 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.当您尝试通过with语句之外的 DictReader 访问数据时,DictReader 无法访问已关闭的文件,因此您会收到 IOError。

You can get around this by gathering the rows from the file into a list before returning from the function:在从 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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