How to save a hash to a file?

Asked

Viewed 363 times

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 to use the

'arquivo.write(h)' 

and it didn’t work because it strictly asks for strings, so I would like to know what I can use to save the hashs in a file.

1 answer

1

You cannot save Dict(hash) to a file because it is a data structure in memory. You need a way to represent this data structure so that you can write it on disk, this is called serialization.

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


Pickle

python has a specific library for object serialization, called pickle, that you can use to achieve your 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 recover the file object:

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 turn it into a string in JSON format, and save the string to a file, provided that 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, because 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.