【问题标题】:how do i get a dict as dict back from csv fille我如何从 csv 文件中获取 dict 作为 dict 返回
【发布时间】:2020-05-17 20:49:33
【问题描述】:

你好我想在我的 csv 文件中写一个字典,然后当我阅读它时将它作为字典返回我在一些 python 论坛中搜索并且还看到了这个“csv dictreader”但我不知道如何正确使用它所以我在这里问。 我想象它是这样的,但这不起作用

x = open('file','w')
a = {}
a['hi'] = 'yes'
x.write(str(a))
x.close
x = open('file','r')
a = x.read()

然后我想把它作为字典拿回来

print(a['hi])

我这样做是为了测试它,但我只是得到一个字符串,我需要把它写成一个字符串,因为我不能在 csv 文件中写 dicts 你有什么解决方案可以帮助我解决我的问题吗? 谢谢。

【问题讨论】:

    标签: python csv dictionary


    【解决方案1】:

    您可以使用 Python pickle 模块。

    在你的情况下,用法是:

    # Write the dict
    pickle.dump(a, open("file", "wb"))
    
    # Read the dict
    a = pickle.load(open("file", "rb"))
    

    【讨论】:

      【解决方案2】:

      也许更好的解决方案是将文件写入 json fromat insted 的 csv 格式。使用 json.dumps 将数据结构(例如,带有整数的列表的字典)转换为 json 表示(字符串)。然后将其写入文件。从文件中读取的内容(带有 json 表示的字符串)可以使用 json.loads 转换为数据结构。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-24
        • 2015-06-25
        • 2018-08-04
        • 2022-11-17
        • 2011-03-19
        • 1970-01-01
        • 2019-01-10
        • 2013-04-20
        相关资源
        最近更新 更多