0
I have a code that accesses a CSV file through a function. I created a second function to change the header name of the columns (change name) and not to have to call it several times by changing the parameters of "colunaIngles" and "colunaPortugues" - a call for each column -, created a support function (change NomeSupporte) which takes the keys (Keys) and values (values) of a dictionary and passes as an argument in the call of the main function (alterName).
That is, it is a function that calls another function using the keys and values of a dictionary as parameters.
It turns out that gives the error "Typeerror: unhashable type: 'dict_keys'" and I can’t solve, I tried to convert to list and frozenset but it was unsuccessful.
Any idea how to solve?
CSV access script:
import unicodecsv
def lerCsv(arquivo):
with open(arquivo, 'rb') as dados:
dicionario = unicodecsv.DictReader(dados)
return list(dicionario)
envolvimentoDiario = lerCsv('envolvimento_diario.csv')
Script with functions for changing column keys:
envolvimentoNomesColunas = {'acct': 'id_conta', 'utc_date': 'data'}
chaves = envolvimentoNomesColunas.keys()
valores = envolvimentoNomesColunas.values()
def alterarNomeSuporte(arquivo):
for coluna in arquivo:
alterarNome(arquivo, chaves, valores)
def alterarNome(arquivo, colunaIngles, colunaPortugues):
for coluna in arquivo:
coluna[colunaPortugues] = coluna[colunaIngles] (colunaPortugues) cujos valores são iguais ao da colunaIngles
del[coluna[colunaIngles]]
alterarNomeSuporte(envolvimentoDiario)
print (envolvimentoDiario[0])
Thank you!
Hello, so, I had already tried exactly as you said. When I convert to frozenset it returns me this error: "Keyerror: frozenset({'utc_date', 'acct'})"
– Cristhian Miguel
their variable names are confused, and it is difficult to keep track of what is happening - in particular you have a "file" parameter in your functions that actually contains a list which was read in the
leCSV
. I strongly recommend that you go refactoring your program to media that will change the same of fforma uqe variable names make sense, otherwise it won’t be hard for other people to look at your code, as it will be complicated for you to even see this code back in a few weeks.– jsbueno
Said the above: of course for the key to exist in the dictionary, the dictionary keys have to be frozensets themselves: anywhere you create the dictionary that is called
coluna
within the methodalterarNome
, You must apply the frozenset transform before making the assignment. The names are so strange, and maybe I’m missing a part, that I can’t tell why thiscoluna
is a dictionary "at all".– jsbueno
Ah - understood now, its variable "dictionary" in "leCSV" is not a dictionary itself, but a
dictReader
, and the function returns a list of dictionaries. (How about calling the variable ofreader
orleitor
if that’s what’s inside it? ) I’ll edit the answer then. , what should Voce do.– jsbueno