Hoe kan ik augurk gebruiken om een dictaat op te slaan?

Ik heb de informatie bekeken die de Python-documentengeven, maar ik ben nog een beetje in de war. Kan iemand voorbeeldcode posten die een nieuw bestand zou schrijven en vervolgens augurk gebruiken om er een woordenboek in te dumpen?


Antwoord 1, autoriteit 100%

Probeer dit:

import pickle
a = {'hello': 'world'}
with open('filename.pickle', 'wb') as handle:
    pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL)
with open('filename.pickle', 'rb') as handle:
    b = pickle.load(handle)
print a == b

Antwoord 2, autoriteit 12%

import pickle
your_data = {'foo': 'bar'}
# Store data (serialize)
with open('filename.pickle', 'wb') as handle:
    pickle.dump(your_data, handle, protocol=pickle.HIGHEST_PROTOCOL)
# Load data (deserialize)
with open('filename.pickle', 'rb') as handle:
    unserialized_data = pickle.load(handle)
print(your_data == unserialized_data)

Het voordeel van HIGHEST_PROTOCOLis dat bestanden kleiner worden. Dit maakt het ontbeitsen soms veel sneller.

Belangrijke opmerking: de maximale bestandsgrootte van augurk is ongeveer 2 GB.

Alternatieve manier

import mpu
your_data = {'foo': 'bar'}
mpu.io.write('filename.pickle', data)
unserialized_data = mpu.io.read('filename.pickle')

Alternatieve formaten

Voor uw aanvraag kan het volgende van belang zijn:

  • Ondersteuning door andere programmeertalen
  • Lees-/schrijfprestaties
  • Compactheid (bestandsgrootte)

Zie ook: Vergelijking van gegevensserialisatie-indelingen

Als je liever op zoek bent naar een manier om configuratiebestanden te maken, lees dan misschien mijn korte artikel Configuratiebestanden in Python


Antwoord 3, autoriteit 3%

# Save a dictionary into a pickle file.
import pickle
favorite_color = {"lion": "yellow", "kitty": "red"}  # create a dictionary
pickle.dump(favorite_color, open("save.p", "wb"))  # save it into a file named save.p
# -------------------------------------------------------------
# Load the dictionary back from the pickle file.
import pickle
favorite_color = pickle.load(open("save.p", "rb"))
# favorite_color is now {"lion": "yellow", "kitty": "red"}

Antwoord 4, autoriteit 2%

Over het algemeen zal het picken van een dictmislukken, tenzij je er alleen simpele objecten in hebt, zoals strings en integers.

Python 2.7.9 (default, Dec 11 2014, 01:21:43) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from numpy import *
>>> type(globals())     
<type 'dict'>
>>> import pickle
>>> pik = pickle.dumps(globals())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1374, in dumps
    Pickler(file, protocol).dump(obj)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump
    self.save(obj)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 306, in save
    rv = reduce(self.proto)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
    raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle module objects
>>> 

Zelfs een echteenvoudig dictzal vaak mislukken. Het hangt gewoon van de inhoud af.

>>> d = {'x': lambda x:x}
>>> pik = pickle.dumps(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1374, in dumps
    Pickler(file, protocol).dump(obj)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump
    self.save(obj)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 748, in save_global
    (obj, module, name))
pickle.PicklingError: Can't pickle <function <lambda> at 0x102178668>: it's not found as __main__.<lambda>

Als u echter een betere serializer zoals dillof cloudpicklegebruikt, kunnen de meeste woordenboeken worden gebeitst:

>>> import dill
>>> pik = dill.dumps(d)

Of als u uw dictin een bestand wilt opslaan…

>>> with open('save.pik', 'w') as f:
...   dill.dump(globals(), f)
... 

Het laatste voorbeeld is identiek aan alle andere goede antwoorden die hier zijn gepost (die, afgezien van het verwaarlozen van de bewerkbaarheid van de inhoud van het dict, goed zijn).


Antwoord 5

>>> import pickle
>>> with open("/tmp/picklefile", "wb") as f:
...     pickle.dump({}, f)
... 

normaal gesproken verdient het de voorkeur om de cPickle-implementatie te gebruiken

>>> import cPickle as pickle
>>> help(pickle.dump)
Help on built-in function dump in module cPickle:
dump(...)
    dump(obj, file, protocol=0) -- Write an object in pickle format to the given file.
    See the Pickler docstring for the meaning of optional argument proto.

Antwoord 6

Eenvoudige manier om Python-gegevens (bijv. woordenboek) naar een augurkbestand te dumpen.

import pickle
your_dictionary = {}
pickle.dump(your_dictionary, open('pickle_file_name.p', 'wb'))

Antwoord 7

Als je het dictaat alleen in één bestand wilt opslaan, gebruik dan pickleop die manier

import pickle
a = {'hello': 'world'}
with open('filename.pickle', 'wb') as handle:
    pickle.dump(a, handle)
with open('filename.pickle', 'rb') as handle:
    b = pickle.load(handle)

Als u meerdere woordenboeken in meerdere bestanden wilt opslaan en herstellen voor:
caching en opslag van complexere gegevens,
gebruik anycache.
Het doet alle andere dingen die je nodig hebt rond pickle

from anycache import anycache
@anycache(cachedir='path/to/files')
def myfunc(hello):
    return {'hello', hello}

Anycache slaat de verschillende myfuncresultaten op, afhankelijk van de argumenten om
verschillende bestanden in cachediren laadt ze opnieuw.

Zie de documentatievoor meer informatie.


Antwoord 8

import pickle
dictobj = {'Jack' : 123, 'John' : 456}
filename = "/foldername/filestore"
fileobj = open(filename, 'wb')
pickle.dump(dictobj, fileobj)
fileobj.close()

Antwoord 9

Ter info, Panda’s hebben nu een methode om augurken te bewaren.

Ik vind het makkelijker.

pd.to_pickle(object_to_save,'/temp/saved_pkl.pickle' )

Antwoord 10

import joblib
my_dict = {'hello': 'world'}
joblib.dump(my_dict, "my_dict.pickle")
my_dict_loaded = joblib.load("my_dict.pickle")

Antwoord 11

Ik heb beitsen verwarrend gevonden (mogelijk omdat ik dik ben). Ik ontdekte echter dat dit werkt:

myDictionaryString=str(myDictionary)

Die u vervolgens naar een tekstbestand kunt schrijven. Ik gaf het op om augurk te gebruiken omdat ik fouten kreeg die me vertelden om gehele getallen naar een .dat-bestand te schrijven. Mijn excuses voor het niet gebruiken van augurk.

Other episodes