Problem searching and filtering date data on object

Asked

Viewed 93 times

0

I have the following functions to search and sort a user for a certain date, however, when running these functions on an object, it generates an error KeyError: 0 in function listagemData

#Criar padrão para pesquisa por data
def criarStrData():
    ano = input("Por favor, informe o ANO para a busca (ex.: 1905)\n")
    mes = input("Por favor, informe o MÊS para a busca (ex.: 4, 5, 12)\n")
    dia = input("Por favor, informe o DIA para a busca (ex.: 15, 2, 29)\n")
    #Dia, Mês e Ano
    mda = "{}/{}/{}".format(mes,dia,ano)
    return mda

#Usar padrão para buscar usuários e inserí-los em listagem
def listagemData(usuarios, mda):
    listagemDt = []
    for i in range(0, len(usuarios)):
        print(usuarios[i])
        if usuarios[i][3][0] == mda:
            listagemDt.append(usuarios[i])
    return listagemDt

#Filtrar a lista em ordem
def filtroDt(listagemDt):
    elementos = len(listagemDt) - 1
    ordenado = False
    while not ordenado:
        ordenado = True
        for i in range(elementos):
            if datetime.datetime.strptime(listagemDt[i][3][1], "%H:%M") > datetime.datetime.strptime(listagemDt[i + 1][3][1], "%H:%M"):
                listagemDt[i], listagemDt[i + 1] = listagemDt[i + 1], listagemDt[i]
                ordenado = False
    return listagemDt`

Use of functions occurs as follows::

listaDtF = filtroDt(listagemData(usuarios, criarStrData()))
if len(listaDtF) > 0:
    for i in range(0, len(listaDtF)):
        print(listaDtF[i])    
    else:
        print("Nenhum registro encontrado\n")

the verified object is the user object:

{
    "murilomelo": ["Murilo Henrique Gamb\u00f4a de Melo", "Super Administrador de Sistema", 4, ["06/04/2019", "10:13"]],
    "Marcelo": ["Marcelo Almeida", "Administrador", 4, ["06/04/2019", "10:29"]],
    "AdrianaNeves": ["Adriana Neves Castro", "secret\u00e1ria", 1, ["06/04/2019", "10:30"]]
}

How can I fix the code to search and filter the display of this object?

1 answer

1


Man from what I saw Oce is trying to iterate over dictionaries as if it were a list, in python it is not possible to access a dictionary by syntax foo[2] for example, unless 2 be the key to this dictionary, the correct would be foo["key"]. I took your job listagemData and changed the access to the values of the dictionary, it was like this

    def listagemData(usuarios, mda):
    listagemDt = []
    for chave, valor in usuarios.items():
        print(valor)
        if valor[3][0] == mda:
            listagemDt.append({chave: valor})
    return listagemDt
  • Anderson helped me chat, I’ll run here, if it works already mark as answer, because that’s right

Browser other questions tagged

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