Save a dictionary to a file (alternative to pickle) in Python?

后端 未结 6 1098
忘掉有多难
忘掉有多难 2020-12-12 12:41

Answered I ended up going with pickle at the end anyway

Ok so with some advice on another question I asked I was told to use pickle to save a dictio

6条回答
  •  鱼传尺愫
    2020-12-12 13:20

    Sure, save it as CSV:

    import csv
    w = csv.writer(open("output.csv", "w"))
    for key, val in dict.items():
        w.writerow([key, val])
    

    Then reading it would be:

    import csv
    dict = {}
    for key, val in csv.reader(open("input.csv")):
        dict[key] = val
    

    Another alternative would be json (json for version 2.6+, or install simplejson for 2.5 and below):

    >>> import json
    >>> dict = {"hello": "world"}
    >>> json.dumps(dict)
    '{"hello": "world"}'
    

提交回复
热议问题