Python:将字典保存到.py文件

3

我有一个在Python脚本中产生的字典this_dict,我想将它写入一个单独的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
                     }
            }

1
为什么你不使用pickle呢? - undefined
似乎更容易的方法是将文件作为json加载,而不是生成源代码。this_dict = json.load(open("dict_file.json")) - undefined
pickle的第二种用法:https://dev59.com/VW855IYBdhLWcg3wGQbY - undefined
字典没有名称。 - undefined
2个回答

3

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)

0

如果你不想在评论中使用pickle,如@roganjosh建议的那样,一个巧妙的解决方法是以下:

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不会有其他的打印语句。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接