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

后端 未结 6 1086
忘掉有多难
忘掉有多难 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:15

    The YAML format (via pyyaml) might be a good option for you:

    http://en.wikipedia.org/wiki/Yaml

    http://pypi.python.org/pypi/PyYAML

    0 讨论(0)
  • 2020-12-12 13:17

    While I'd suggest pickle, if you want an alternative, you can use klepto.

    >>> init = {'y': 2, 'x': 1, 'z': 3}
    >>> import klepto
    >>> cache = klepto.archives.file_archive('memo', init, serialized=False)
    >>> cache        
    {'y': 2, 'x': 1, 'z': 3}
    >>>
    >>> # dump dictionary to the file 'memo.py'
    >>> cache.dump() 
    >>> 
    >>> # import from 'memo.py'
    >>> from memo import memo
    >>> print memo
    {'y': 2, 'x': 1, 'z': 3}
    

    With klepto, if you had used serialized=True, the dictionary would have been written to memo.pkl as a pickled dictionary instead of with clear text.

    You can get klepto here: https://github.com/uqfoundation/klepto

    dill is probably a better choice for pickling then pickle itself, as dill can serialize almost anything in python. klepto also can use dill.

    You can get dill here: https://github.com/uqfoundation/dill

    0 讨论(0)
  • 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"}'
    
    0 讨论(0)
  • 2020-12-12 13:24

    Although, unlike pp.pprint(the_dict), this won't be as pretty, will be run together, str() at least makes a dictionary savable in a simple way for quick tasks:

    f.write( str( the_dict ) )
    
    0 讨论(0)
  • 2020-12-12 13:29

    You asked

    Ill give it a shot. How do I specify what file to dump it to/load it from?

    Apart from writing to a string, the json module provides a dump()-method, which writes to a file:

    >>> a = {'hello': 'world'}
    >>> import json
    >>> json.dump(a, file('filename.txt', 'w'))
    >>> b = json.load(file('filename.txt'))
    >>> b
    {u'hello': u'world'}
    

    There is a load() method for reading, too.

    0 讨论(0)
  • 2020-12-12 13:33

    The most common serialization format for this nowadays is JSON, which is universally supported and represents simple data structures like dictionaries very clearly.

    >>> members = {'Starspy' : 'SHSN4N', 'Test' : 'Test1'}
    >>> json.dumps(members)
    '{"Test": "Test1", "Starspy": "SHSN4N"}'
    >>> json.loads(json.dumps(members))
    {u'Test': u'Test1', u'Starspy': u'SHSN4N'}
    
    0 讨论(0)
提交回复
热议问题