简体   繁体   English

完全按照变量中的定义输出字典到文件

[英]Outputting a dictionary to file exactly as defined in variable

I am wondering if there is a way to output a dictionary to a file exactly as it would be defined as a variable? 我想知道是否有一种方法可以将字典输出到文件中,就像它被定义为变量一样?

So if in code it looks like: 因此,如果在代码中它看起来像:

dict1 = {01: 'val1', 02: 'val2', 03: 'val3'}

the contents of the file would look identical? 文件的内容看起来一样吗?

So file contains: 所以文件包含:

dict1 = {01: 'val1', 02: 'val2', 03: 'val3'}

I've heard of pickle and JSON but I ideally want to be able to import them from a module, ie 我听说过pickle和JSON但我理想的是希望能够从模块中导入它们,即

from some_module import some_dict

Is this possible? 这可能吗?

Simply use the built-in repr(...) function that converts objects to a string in that way that the resulting string is a valid literal with which you could recreate the object. 只需使用内置的repr(...)函数,该函数将对象转换为字符串,使得结果字符串是一个有效的文字,您可以使用该文字重新创建对象。

It calls its argument's __repr__() method which at least produces valid literals for the most common basic data types. 它调用其参数的__repr__()方法,该方法至少为最常见的基本数据类型生成有效的文字。 It does not work for most other objects though: 但它对大多数其他对象不起作用:

dict1 = {1: 'val1', 2: 'val2', 3: 'val3'}
literal = repr(dict1)

print(literal)
# Output: {1: 'val1', 2: 'val2', 3: 'val3'}

Now you could store that in a Python file: 现在您可以将其存储在Python文件中:

with open("my_dict.py", "w") as f:
    print("dict2 = " + literal, file=f)

And this is now importable as module from other Python scripts inside the same folder: 现在,这可以从同一文件夹中的其他Python脚本作为模块导入:

import my_dict
print(my_dict.dict2[2])
# Output: val2

Or if you don't want to use the module name each time, import it using from : 或者,如果你不想每次使用模块名,使用导入from

from my_dict import dict2
print(dict2[2])
# Output: val2

I don't think that is possible. 我不认为这是可能的。 Imports are used for importing modules, not files. 导入用于导入模块,而不是文件。 You will need to read and process the file in order for this to work. 您需要阅读并处理该文件才能使其正常工作。 You can write the dict to a file with for example: 您可以将dict写入文件,例如:

output = "dict1 = "+str(dict1) 
f.write(output)

You can achieve an objects name by using the globals() function which shows you a dictionary over the current state of the module. 您可以使用globals()函数来实现对象名称,该函数向您显示模块当前状态的字典。 But this is not a good scenario, you should use serialization of your data, maybe by JSON. 但这不是一个好的场景,你应该使用数据的序列化,也许是通过JSON。

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

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