【问题标题】:Python: Saving dictionary to .py filePython:将字典保存到 .py 文件
【发布时间】:2018-03-22 23:22:19
【问题描述】:

我有一个字典 this_dict 在 python 脚本中生成,我想将其写入单独的 python 模块 dict_file.py。这将允许我通过导入 dict_file 在另一个脚本中加载字典。

我认为一种可能的方法是使用 JSON,所以我使用了以下代码:

import json

this_dict = {"Key1": "Value1",
             "Key2": "Value2",
             "Key3": {"Subkey1": "Subvalue1",
                      "Subkey2": "Subvalue2"
                     }
            }

with open("dict_file.py", "w") as dict_file:
    json.dump(this_dict, dict_file, indent=4)

当我在编辑器中打开生成的文件时,我得到了一本印刷精美的字典。但是,脚本中的字典名称(this_dict)没有包含在生成的dict_file.py 中(所以只写了字典的大括号和正文)。我怎样才能包括字典的名称呢? 我希望它生成dict_file.py,如下所示:

this_dict = {"Key1": Value1,
             "Key2": Value2,
             "Key3": {"Subkey1": Subvalue1,
                      "Subkey2": Subvalue2
                     }
            }

【问题讨论】:

  • 你为什么不改用pickle
  • 似乎更容易将文件加载为 json this_dict = json.load(open("dict_file.json")) 而不是生成源代码。
  • 字典没有名字。

标签: python json file dictionary


【解决方案1】:

1) 使用 file.write:

file.write('this_dict = ')
json.dump(this_dict, dict_file)

2)使用write + json.dumps,返回带有json的字符串:

file.write('this_dict = ' + json.dumps(this_dict)

3) 直接打印,或者使用 repr

file.write('this_dict = ')
file.write(repr(this_dict))
# or:
# print(this_dict, file=file)

【讨论】:

    【解决方案2】:

    如果您不想像 cmets 中建议的 @roganjosh 那样使用 pickle,则可以采用以下解决方法:

    this_dict = {"Key1": "Value1",
                 "Key2": "Value2",
                 "Key3": {"Subkey1": "Subvalue1",
                          "Subkey2": "Subvalue2"
                         }
                }
    
    # print the dictionary instead
    print 'this_dict = '.format(this_dict)
    

    并将脚本执行为:

    python myscript.py > dict_file.py
    

    注意:当然这是假设您在myscript.py 上没有任何其他打印语句。

    【讨论】:

      猜你喜欢
      • 2016-03-29
      • 1970-01-01
      • 2017-07-14
      • 2017-11-23
      • 2021-03-23
      • 2022-12-15
      • 1970-01-01
      • 2011-06-21
      • 2021-07-04
      相关资源
      最近更新 更多