gpt4 book ai didi

python - 如何从文件创建嵌套字典列表

转载 作者:行者123 更新时间:2023-11-28 17:03:26 25 4
gpt4 key购买 nike

我有一个包含键/值对列表的输入文本文件,我想将其作为字典列表读入 python,但似乎无法使其按预期工作。请注意,该文件不是有效的 json 格式,所以我不能使用内置的 json,这个问题不是 this 的副本.我怀疑我在这里遗漏了一些明显的东西,因此非常感谢任何指导。

# /tmp/tmp.txt
[{'k1': {'k2': {'k3': ['a', 'b', 'c']}}}, {'k4': {'k5': {'k6': ['v', 'x', 'y', 'z']}}}]

因为这个文件包含一个包含 2 个元素的列表,我希望 len 为 2 而 typelist 但是这不是我所看到的。

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'>

最佳答案

您的数据 是一个字符串。您可以使用 literal_eval 将其转换为列表:

import ast
data_list = ast.literal_eval(data)
len(data_list)
#2

关于python - 如何从文件创建嵌套字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52771867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com