File for dictionary

0

I'm trying to transform a file into a dictionary but it's giving the following error:

  

Traceback (most recent call last): File   "C: \ Users \ taynan \ AppData \ Local \ Programs \ Python \ Python36-32 \ Project   CRUD \ Interface.py ", line 46, in       consultProfessor (cpfP, arqProfessors) File "C: \ Users \ taynan \ AppData \ Local \ Programs \ Python \ Python36-32 \ Project   CRUD \ ModuloDeFuncoes.py ", line 38, in consultingProfessor       key, val = line [: - 1] .split () ValueError: not enough values to unpack (expected 2, got 0)

Can anyone identify where the error is? Because I do not know: /

File:

{'Nome': 'd', 'Cpf': '33', 'Departamento': 'a'}
{'Nome': 'f', 'Cpf': '22', 'Departamento': 'g'}
{'Nome': 'a', 'Cpf': '13', 'Departamento': 'b'}
{'Nome': 'x', 'Cpf': '24', 'Departamento': 'd'}

Here's part of the code, because it's too big:

def consultarProfessor(cpf, arquivoEspecifico):
arquivo = lerArquivo(arquivoEspecifico)
for linha in arquivo:
    linha = linha.replace('"',"")
    chave, valor = linha[:-1].split()
    dicProfessores[chave] = valor
if cpf in dicProfessores.values():
    dicProfessor = dicProfessores[cpf]
    arquivo.close()                                            #definindo uma variavel para a chave do dicionario de professores
    print(dicProfessores)
else:
    print("Este professor não é funcionário desta faculdade.")

Obs. I've already tried using dicProfessores = eval(linha[-1]) , but it was making a lot of errors.

#Edit: Consegui criar o dicionário, mas ele está saindo todo errado:
def file_to_dict(arquivoEspecifico):
dic = {}
arquivo = lerArquivo(arquivoEspecifico)
for linha in arquivo:
    linha = linha.replace('"',"")
    valor = linha[:-1].split()
    chave = linha[:-1].split()
    for v in valor:
        v = v.replace(",","")
        v = v.replace("{","")
        v = v.replace("}","")
        v = v.replace(":","")
        v = v.replace("'","")
        for c in chave:
            c = c.replace(",","")
            c = c.replace("{","")
            c = c.replace("}","")
            c = c.replace(":","")
            c = c.replace("'","")
            dic[c] = v
print(dic)
return dic

Here's how it's coming out:

{'Nome': 'g', 'd': 'a', 'Cpf': 'g', '33': 'a', 'Departamento': 'g', 'a': 'a', 'f': 'g', '22': 'g', 'g': 'g'}
    
asked by anonymous 01.08.2017 / 19:52

2 answers

0

Friend, your error is on the line

chave, valor = linha[:-1].split()

this assignment is not allowed for this particular case Well I've tested the assignments separately and worked out that way

chave = linha[:-1].split()
valor = linha[:-1].split()

as shown in the

Butthatalonedoesnotsolveyourproblem...thatsaidIdidthisfunctionalimplementation

#Essecódigoserveseseguiressemodelo#Essemodelofoiusadocomoexemplo->suponhaquelinha="{'Nome': 'd', 'Cpf': '33', 'Departamento': 'a'}" 
dict = {}
for linha in arquivo:
    linha = linha.replace("'", "")

    b = linha.split(',')

    for i in b:
        c  = i.split(':')
        c[0] = c[0].replace("{","")
        c[0] = c[0].replace("}","")
        c[0] = c[0].replace(":","")
        c[1] = c[1].replace("{","")
        c[1] = c[1].replace("}","")
        c[1] = c[1].replace(":","")
        dict[c[0]] = c[1]
print dict

The code results in a dictionary with keys and values:

    
01.08.2017 / 20:46
0

The json module can make it easier to build your function. The loads () function turns str into dict with the need to follow only some pre-established rules. In your case, the only things you will have to deal with are the single quotes and the line breaks. But these issues can be fixed with the .replace () you're already using.

As your code is not indented, I do not understand if you intend to make a dictionary with all the data, and then only make the query, or if you want to do the query line by line.

If you just make the query line by line, you can do this:

import json

def consultarProfessor(cpf, arquivoEspecifico):
    with open(arquivoEspecifico, "r") as arquivo:
        for li in arquivo:
            li = li.replace("'", "\"")
            li = li.replace("/n", "")
            li = json.loads(li)   # <-- Transforma str em dict
            if str(cpf) == li["Cpf"]:
                return li
        return "Não encontrado"

file = "lista.txt"
cpf_consult = 24

print(consultarProfessor(cpf_consult, file))
    
04.08.2017 / 19:50