[英]How to create list of nested dictionaries from file
I have an input text file containing a list of key/value pairs that I would like to read into python as a list of dictionaries but can not seem to get it to work as expected. 我有一个输入文本文件,其中包含一个键/值对列表,我想将其作为字典列表读入python但似乎无法使其按预期工作。 Note that the file is not in valid json format so I can not use the json
built-in and this question is not a duplicate of this . 请注意,该文件是不是有效的JSON格式,所以我不能使用json
内置的这个问题是不是重复这个 。 I suspect that I am missing something obvious here so any guidance is much appreciated. 我怀疑我错过了一些明显的东西,所以任何指导都非常感谢。
# /tmp/tmp.txt
[{'k1': {'k2': {'k3': ['a', 'b', 'c']}}}, {'k4': {'k5': {'k6': ['v', 'x', 'y', 'z']}}}]
Since this file contains a list with 2 elements, I would expect the len
to be 2 and the type
to be list
but that is not what I'm seeing. 由于这个文件包含一个包含2个元素的列表,我希望len
为2并且type
为list
但这不是我所看到的。
with open('/tmp/tmp.txt', encoding='utf-8') as data_file:
data = data_file.read()
print(len(data)) # <-- the goal is for this to show 2
print(type(data)) # <-- the goal is for this to return `list`
88
<class 'str'>
Your data
is a string. 您的data
是一个字符串。 You can convert it to a list with literal_eval
: 您可以使用literal_eval
将其转换为列表:
import ast
data_list = ast.literal_eval(data)
len(data_list)
#2
EDIT: I didn't saw earlier that DYZ answered before me but I would like to explain my answer a bit more. 编辑:我之前没有看到DYZ在我之前回答,但我想更多地解释我的答案。
There is a module called 'ast' that have the function 'literal_eval', as the name suggest, it evaluates the information of the txt as python code and also validates the input. 有一个名为'ast'的模块,其函数为'literal_eval',顾名思义,它将txt的信息作为python代码进行评估,并验证输入。
import os, ast
with open('/tmp/tmp.txt', encoding='utf-8') as data_file:
data = ast.literal_eval(data_file.read())
print(len(data))
print(type(data))
Output: 输出:
2
<class 'list'>
If you're trying to store and retrieve Python objects, serialization is probably a better way to go. 如果您正在尝试存储和检索Python对象,那么序列化可能是更好的方法。 See, for example, the pickle module . 例如,参见泡菜模块 。
But, in the present context, you could use the built-in Python eval function to accomplish your goal. 但是,在目前的上下文中,您可以使用内置的Python eval函数来实现您的目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.