【问题标题】:String to dictionary conversion字符串到字典的转换
【发布时间】:2016-04-08 09:03:00
【问题描述】:

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

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

【问题讨论】:

  • 为什么不以更易于解析的格式导出字典?
  • 不要重新发明轮子,除非是出于培训目的。使用json.dump 将字典转储到文件中并使用json.load 加载它
  • 我建议您使用json 对象来保存您的字典,因为这样您将无法轻松地从文件中读取它
  • 将文本转换为列表并从列表中更新字典。
  • 您介意提供一个您尝试导出到字典中的文本示例吗?

标签: python string dictionary type-conversion


【解决方案1】:

如果你的格式总是像张贴的一样,你可以通过拆分将其解析成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")))

【讨论】:

    【解决方案2】:

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

    #!python3
    import ast
    
    try:
        with open('accounts.txt') as f:
            accounts=ast.literal_eval(f.read())
    except FileNotFoundError:
        accounts = {}
    
    username = input('User name? ')
    password = input('Password? ')
    accounts[username] = password
    
    with open('accounts.txt','w') as f:
        f.write(str(accounts))
    

    例子:

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

    【讨论】:

      【解决方案3】:

      是否可以将所有帐户加载到内存中?如果是这样,最简单的方法是将内容加载并写入为 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)
      

      【讨论】:

        【解决方案4】:

        你可以使用 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 保存它

        【讨论】:

          猜你喜欢
          • 2017-03-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-25
          • 2011-02-16
          • 1970-01-01
          相关资源
          最近更新 更多