在用例中学习python-词典作为一个全局工具?

在用例中学习python-词典作为一个全局工具?,python,dictionary,Python,Dictionary,我正在学习python,并希望了解正确的python代码方法 我正在写一个实用程序 读取文件名和搜索词的列表 打开每个文件,搜索术语并从匹配行中提取一些数据 构造一个字典来保存标签术语和值 将此词典输出到CSV文件 我有代码在工作-我有一些整理和一些精简-但想了解最佳实践方法 因此,流程如下所示: create global dictionary report_outer_loop() print_dict() report_outer_loop open the list of repo

我正在学习python,并希望了解正确的python代码方法

我正在写一个实用程序

  • 读取文件名和搜索词的列表
  • 打开每个文件,搜索术语并从匹配行中提取一些数据
  • 构造一个字典来保存标签术语和值
  • 将此词典输出到CSV文件
  • 我有代码在工作-我有一些整理和一些精简-但想了解最佳实践方法

    因此,流程如下所示:

    create global dictionary
    report_outer_loop()
    print_dict()
    
    report_outer_loop
      open the list of reports
      for each item in list (the item contains report name, search term, etc)
        call report_inner_loop (item)
    
    report_inner_loop (item)
      get reportname from item
      get search term from item  
      open report
      for each line in report
        find search_term
        update dictionary with extracted data
    
    print_dict()
      for each item in dictionary
      write key, value to file
    
    所以,你可以看到我有一个全局字典,可以通过内部循环和print_dict访问。 我的问题是:这是正确的python方法吗?
    或者我不应该将其创建为全局函数,而是将其传递到外部_循环,然后传递到内部,再传递到打印函数?

    还是有更好的方法?

    我会在
    报告外循环中创建一个本地字典,将它传递到
    报告内循环,并在运行
    报告外循环时返回它

    您可以将
    dict
    子类化,将您的
    report\u outer\u循环添加为
    append\u reports
    函数。然后,你可以简单地使用self.append(extracted_data)

    将这些方法包装到一个类中,并将该dict作为类实例的属性,怎么样?@tobias_k,或者你可以简单地将其子类
    dict
    本身添加到类中,谢谢Tomo-我已经选择了这一个作为最佳答案,因为到目前为止,我还不知道如何创建类!毫无疑问,随着我学习更多python,我将重新调整此代码@AstroDaz两种方法都很好(而且比全局变量好得多)。虽然就我个人而言,如果可能的话,我不喜欢操纵函数参数(除了
    self