Dictionary file

Asked

Viewed 569 times

0

I am trying to turn a file into dictionary but is 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 consultarProfessor(cpfP, arqProfessores) File "C: Users taynan Appdata Local Programs Python Python36-32 Project CRUD Modulodefuncoes.py", line 38, in consultarProfessor key, val = line[:-1]. split() Valueerror: not enough values to unpack (expected 2, got 0)

Can anyone identify where the bug is? Because I don’t know :/

Filing cabinet:

{'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 is a part of the code, because it is very large:

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 tried using dicProfessores = eval(linha[-1]), but it was making a lot of mistakes.

#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'}
  • Type the teacher’s Cpf: 33 [] Traceback (Most recent call last): File "C: Users taynan Appdata Local Programs Python Python36-32 Project CRUD Interface.py", line 46, in <module> consultarProfessor(cpfP, arqProfessores) File "C: Users taynan Appdata Local Programs Python Python36-32 CRUD Project Modulodefuncoes.py", line 38, in consultarProfessor key, val = print(line[:-1].split()) Typeerror: 'Nonetype' Object is not iterable Ta saying that the list ta did, ta error in the split I think :/

2 answers

1

The module json can facilitate the construction of its function. The function loads() turns str into Dict with the need to follow only a few pre-established rules. In your case, the only things you will have to deal with are the simple quotes and line breaks. But these questions can be corrected with the .replace() that you are already using.

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

If you are just doing the query line by line, you can do so:

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))
  • God, I don’t know how to thank you. If I win the 3 points on this project I will dedicate to you kkkkkkk And thank you to everyone who tried to help :D

0

Buddy, your mistake is on the line

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

such allocation is not permitted for that particular case Well I tested the assignments separately and it worked out that way

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

as shown at the prompt inserir a descrição da imagem aqui

However, that alone does not solve your problem... that said I made this implementation functional

# Esse código serve se seguir esse modelo  
# Esse modelo foi usado como exemplo -> suponha que linha = "{'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:

inserir a descrição da imagem aqui

  • Po mano vlw mesmo, I had no idea, but now I’m giving this error: Traceback (Most recent call last): File "C: Users taynan Appdata Local Programs Python Python36-32 CRUD Interface.py Project", line 46, in <module> consultarProfessor(cpfP, arqProfessores) File "C: Users taynan Appdata Local Programs Python Python36-32 CRUD Project Modulodefuncoes.py", line 40, in consultarProfessor dicProfessores[key] = val Typeerror: unhashable type: 'list'

  • Only that I put so also: dicProfessores[key] = value

  • so look at this resolution that I just edited in response.

  • Generated a dictionary with the information

  • Thanks friend, I made a function to turn file into dictionary using your code, but I’ve tried several ways to fix your code, but it keeps giving this error: File "C:\Users\taynan\AppData\Local\Programs\Python\Python36-32\Projeto CRUD\ModuloDeFuncoes.py", line 54, in consultarProfessor&#xA; dicProfessores = file_to_dict(arquivoEspecifico)&#xA; File "C:\Users\taynan\AppData\Local\Programs\Python\Python36-32\Projeto CRUD\ModuloDeFuncoes.py", line 35, in file_to_dict c[1] = c[1]. replace("{","") Indexerror: list index out of range

  • by the tests I did it is not storing the values of the dictionary, which in case would be the c[1]

  • I managed to create the dictionary, is there in the post edition

Show 2 more comments

Browser other questions tagged

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