字符串到字典转换

时间:2016-01-04 17:20:48

标签: python string dictionary type-conversion

我的代码涉及以字典的形式导入和导出用户名和密码。为了导出字典,我将其更改为字符串。 这是导入的文本文件(它的格式与代码导出的格式相同):

{'account1': 'password'}{'account2': 'password'}

要导出的代码如下:

accounts=open("accounts.txt","r")
accounts=accounts.read()

newaccount={username:password}#user name and password are user defined 
str1=str(newaccount)
updated=open("accounts.txt","w")
updated.write(accounts)
updated.write(str1)
updated.close()

我希望字典看起来像这样:

{'account1':'password', 'account2':'password'}

4 个答案:

答案 0 :(得分:2)

如果您的格式总是像发布的那样,您可以通过拆分将其解析为dicts:

from ast import literal_eval
with open("in.txt") as f:
    d = {}
    for line in f:
        ds = [literal_eval(ele + "}") for ele in line.split("}") if ele]
        for _d in ds:
           d.update(_d)
    print(d)

哪个会给你:

{'account2': 'password', 'account1': 'password'}

当你想要保存它时,请自己帮忙并使用json或pickle,即:

from json import dump, load

dump(d, open("in.txt","w"))

然后在需要时加载它:

d = load(open("in.txt")))

答案 1 :(得分:0)

如果您将字典的字符串表示形式转换回字典并更新它,您的方法将起作用:

C:\>test
User name? account1
Password? password

C:\>type accounts.txt
{'account1': 'password'}

C:\>test
User name? account2
Password? password

C:\>type accounts.txt
{'account1': 'password', 'account2': 'password'}

示例:

{{1}}

答案 2 :(得分:-1)

你可以使用python pickle模块:

import pickle
accounts = {'account1': 'password'}{'account2': 'password'}
pickle.dump( accounts, open( "save.p", "wb" ) )

要加载字典,

accounts = pickle.load( open( "save.p", "rb" ) )

您现在可以修改字典并使用pickle.dump

再次保存

答案 3 :(得分:-1)

是否可以在内存中加载所有帐户?如果是这样,最简单的方法是将内容加载并写为json:

import json
with open("accounts.txt", "r") as fp:
   accounts = json.load(fp)
accounts["newUser"] = "password"
with open("accounts.txt", "w") as fp:
   json.dumps(accounts, fp)