Py学习  »  Python

如何在运行的python文件中编辑字典?

Rallph • 4 年前 • 382 次点击  

我是一个初学者,我有一个程序,我试图从用户输入的文件编辑字典。 这就是我所拥有的:

def main():
    dataInfo = {"data1":"12345", "data2":"abc123"}

    addInfo = input(":")
    addInfoValue = input(":")
    dataInfo[addInfo] = addInfoValue

    wantedInfo = input(":")

    try:
        if dataInfo[wantedInfo]:
            print(dataInfo[wantedInfo])
    except KeyError:
        exit()

main()

我做了这个,但是每当我重新启动程序时,我添加到字典中的内容就会被删除。

我想知道是否有办法把写进字典的数据保存下来。我知道有多个文件是有关系的,但不知道怎么做。

这不是确切的文件布局和东西顺便说一句。只是我有麻烦的东西。

另外,删除字典某些部分的方法也会有帮助。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/57033
 
382 次点击  
文章 [ 2 ]  |  最新文章 4 年前
Gabip
Reply   •   1 楼
Gabip    4 年前

如果不将字典写入文件,则无法存储字典,因为它是在内存中管理的。

你可以把字典写成 json 在下一次运行中,您将能够通过读取文件、更新文件并将其再次写入同一个文件(或不同的文件)来读取已写入的值:

import json
with open('path/to/file.json', 'w') as f:
    json.dump(dataInfo, f)

在下一次运行中,您将能够阅读它:

with open('path/to_file.json','r') as f:
    dataInfo = json.load(f)

为了删除字典的键,可以使用 pop() 功能:

dataInfo.pop("data1") # data1 key will be removed from the dict
grandia
Reply   •   2 楼
grandia    4 年前

运行程序时,变量存储在临时存储器(即RAM)中。重新启动程序时,此内存将被清除。

如果您想持久化这些内容,那么您需要以某种方式将它们存储在持久化存储、文本文件或数据库中

下面是一个例子:

import json

some_dict = {'mykey':'myvalue'}

with open('data.txt', 'w') as file:
  # json.dumps will convert your dict into string
  file.write(json.dumps(some_dict))

# read the data from text file
load_dict = {}
with open('data.txt', 'r') as file:
  text_data = file.read()
  # json.loads do the opposite of json.dumps
  load_dict = json.loads(text_data)

所以你要做的就是每次用户输入一些东西,你把dict保存到文本文件中,然后在程序开始时把文本文件加载到dict中