简体   繁体   English

从python中的文本文件初始化字典

[英]Initialising a dictionary from text file in python

I have a complex hierarchical python dictionary like this 我有一个像这样的复杂的分层python字典

      dict = {
               "key1":{"key11":{"a"},"key12":{"b"}},
               "key2":{"key21":{"c"},"key22":{"d"}},
               "key3":{"key31":{"e"},"key32":{"f"}}
             }

      print dict["key2"]["key21"]

The output of this code snippet is "c", so the hierarchical dictionary is interpreted correctly. 此代码段的输出为“ c”,因此可以正确解释分层字典。 Now, instead of hard code this hierarchical dictionary in code, I want to read it from a file and assign it to a dictionary object. 现在,我不想用代码对这个分层词典进行硬编码,而是要从文件中读取它并将其分配给词典对象。 That's to say, I will create a dict.txt file with the following content: 也就是说,我将创建一个具有以下内容的dict.txt文件:

             {
               "key1":{"key11":{"a"},"key12":{"b"}},
               "key2":{"key21":{"c"},"key22":{"d"}},
               "key3":{"key31":{"e"},"key32":{"f"}}
             }

Of course, I will then run to read the stream of the file 当然,然后我将运行以读取文件流

            stream = open("dict.txt", "r")

Then, is there any convenient method in python that allows me to easily assign the content in the stream to a dictionary object dict (not as string)? 然后,python中是否有任何方便的方法可以让我轻松地将流中的内容分配给字典对象dict (而不是字符串)?

我建议您将整个dict = {...}放入文本文件中,将文件命名为something.py ,然后import something并将其直接用作something.dict

If you're sure it's in that exact format, that is valid JSON, so you can use json.load(f) to load and parse it. 如果您确定其格式正确,即是有效的JSON,则可以使用json.load(f)进行加载和解析。

JSON is much pickier than Python though (eg it chokes on trailing commas, and doesn't accept single quotes), so you might need to use ast.literal_eval . JSON比Python更挑剔(例如,它在结尾的逗号中ast.literal_eval ,并且不接受单引号),因此您可能需要使用ast.literal_eval

You could do: 您可以这样做:

import ast
d = ast.literal_eval(stream.read())

But your data is not just a nested dict, rather it has sets as values (at least if one interprets it as Python syntax), which ast.literal_eval can't handle. 但是,您的数据不仅是嵌套的字典,还具有作为值的集合(至少在有人将其解释为Python语法的情况下),而ast.literal_eval无法处理。

From what I understand, that is not a valid JSON for the same reason. 据我了解,出于相同的原因,这不是有效的JSON。

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

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