【问题标题】:Can you append to a dictionary from a foreign python file?您可以从外部 python 文件附加到字典吗?
【发布时间】:2021-02-03 20:38:09
【问题描述】:

所以我有一个我正在做的有趣的项目,但它需要我从另一个 python 文件附加到字典。在file1.py 中看起来像

Name: Eric <-- user input
Age: 27 <-- user input

file2.py

information = {'Eric':27}

我知道我可以在运行代码时临时附加到字典,但在我关闭程序后它似乎会重置。就像最近我在 StackOverflow 问题上看到的一样

d = {'key': 'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'key': 'value', 'mynewkey': 'mynewvalue'}

但这也是,每次运行后都会重置,所以我认为保存字典的唯一方法是将其写入另一个文件。有什么方法可以实现这一目标,或者是更好的选择吗?

【问题讨论】:

  • 我不太确定您要达到的目标。如果你希望你的数据在你关闭程序后仍然存在,你应该写入一个文件。
  • 您可以使用 JSON 将其写入文件。
  • @Filip 我该怎么做?我从来没有真正深入过它。我知道读取和打印 json 数据但不附加到字典的基础知识
  • @Ahmet 我正在尝试将其写入文件。我正在尝试将姓名和年龄等对象输入file1,并将这些对象附加到file2 中的字典中。我只是需要更多关于如何做到这一点的见解

标签: python file dictionary input


【解决方案1】:

您可以使用 JSON 将数据保存到文件中。

这会将存储在字典中的数据保存在一个文件中。

import json

my_dict = {"key": "value", "key2": "value2"}

with open("output_file.txt", "w") as file:
    json.dump(my_dict, file, indent=4)

要再次使用该数据,您可以加载该文件。

import json

with open("output_file.txt") as file:
    my_dict = json.load(file)

print(my_dict)  # Will print {"key": "value", "key2": "value2"}

JSON 代表 JavaScriptObjectNotation,是一种保存数据的方式字符串格式(文件)

所以 JSON 可以将字符串转换为数据,如果它是有效的 JSON:

import json

string_data = '{"key": "value"}'
dictionary = json.loads(string_data)

print(type(string_data))  # <class 'str'>
print(type(dictionary))  # <class 'dict'>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-22
    • 2013-07-13
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多