How to save a hash to a file?

1

Code:

h = {}
arquivo = open("Tabela nome-idade.txt")
r = True
while r:
    nome = str(input("Nome: "))
    if nome == '':
        r = False
        print(h)
        break
    idade = str(input("Idade: "))
    h[nome] = idade

My question is that I tried using

'arquivo.write(h)' 

and it did not work because it strictly asks for strings, so I would like to know what I can use to save the hashes to a file.

    
asked by anonymous 24.02.2017 / 02:43

1 answer

1

You can not save the hash in a file because it is an in-memory data structure. You need a way to represent this data structure so that you can write it to disk, this is called serialization.

There are several ways to serialize objects in python, I'll cite two of them here.

Pickle

Python has a specific library for object serialization, called pickle , which you can use to achieve its goal.

The most basic use would be this way:

import pickle

h = {}
arquivo = open("Tabela nome-idade.pkl", "wb")
r = True
while r:
    nome = str(input("Nome: "))
    if nome == '':
        r = False
        print(h)
        break
    idade = str(input("Idade: "))
    h[nome] = idade

pickle.dump(h, arquivo)
arquivo.close()

And to retrieve the object from the file:

import pickle

arquivo = open("Tabela nome-idade.pkl", "rb")
h = pickle.load(arquivo)
arquivo.close()

JSON

In the specific case of a dict, you could transform it to a string in JSON format, and save the string to a file, as long as the dict contains only other dicts, lists, or strings.

Useful if you want to serialize objects that should be read in programs written in other languages, such as javascript, as all of them will support serialization / deserialization in JSON.

To serialize as JSON:

import json

h = {'a': 1, 'b': [2,3,4]}
j = json.dumps(h)
with open('arquivo.txt', 'w') as arquivo:
   arquivo.write(j)

And to deserialize:

import json

with open('arquivo.txt', 'r') as arquivo:
   j = arquivo.read()
   h = json.loads(j)  # Objeto recuperado
    
24.02.2017 / 03:37