如何通过在字典中成对通过两个列表在 Python 中创建文本文档

How to create Text document in Python through two lists by making pairs in a dictionary

提问人:Hircane 提问时间:1/21/2021 最后编辑:Hircane 更新时间:1/22/2021 访问量:52

问:

我正在尝试创建这个特定的文本文档:

a=1

b=2

c=3

d=4!

通过这两个列表:

keys = ["a", "b", "c", "d"]
values = ["1", "2", "3", 4]

这是我的代码:

import json

keys = ["a", "b", "c", "d"]
values = ["1", "2", "3", 4]

data = {key: val for key, val in zip(keys, values)}

with open('file.txt','w') as f:
    json.dump(data, f,separators=('\n','='))

我的代码如下,但我无法弄清楚如何删除引号或括号。最后,我应该能够在 4 之后创建一个感叹号。 很高兴任何帮助,我对编码很陌生。 我想将列表保存到字典中,然后创建一个带有 for 循环的文本文件。

python json 列表 字典 报价

评论

1赞 deadshot 1/21/2021
你不需要模块。您可以将数据直接写入文件json
0赞 CATboardBETA 1/21/2021
为什么要将库用于纯文本?json

答:

0赞 Daweo 1/21/2021 #1

要创建的文件不是合法的 JSON。使用所谓的 f-string(需要 python 3.6 或更高版本)或其他格式机制可以轻松处理您的任务。例如:

keys = ["a", "b", "c", "d"]
values = ["1", "2", "3", 4]

lines = [f'{key}={val}' for key, val in zip(keys, values)]
lines[-1] = lines[-1] + "!"
text = "\n".join(lines)

with open('file.txt','w') as f:
    f.write(text)

如果你想了解更多关于 f-string 的信息,我建议阅读 realpython 的教程

评论

0赞 deadshot 1/21/2021
您可以直接使用而无需使用writelines()join()
1赞 WSiebelder 1/22/2021 #2

我假设您要打印感叹号,因为元组(具有多个数据类型的列表)中最后一个元素的数据类型不同。

另外,我不清楚你为什么使用 json.dump(...)

用:

if type(values[i]) is int:

您可以检查元素 i 的值是否为 int 类型

用:

if type(values[i]) is not str:

您可以检查元素 i 的值是否不是字符串类型

然后按列表的长度遍历列表,你会得到如下内容:

keys = ["a", "b", "c", "d"]
values = ["1", "2", "3", 4]


F = open("file.txt", "w")
for i in range(len(keys)):
    line =f"{keys[i]}={values[i]}"
    if type(values[i]) is int:
        line+="!"
    F.write(line+"\n")