Home > Net >  Get the value of a specific record in dicts with lists in python
Get the value of a specific record in dicts with lists in python

Time:06-22

I have a dict like this:

contactos = dict([
    "id", id,
    "nombres", nombres,
    "apellidos", apellidos,
    "telefonos", telefonos,
    "correos", correos
])

And it works when I put a new register in every key:value, my problem is, how can I get the record for only one contact? I have a part where I can input a number and search the position in the list of the dict, then I want to only show the record of that specific record in every key:value

I made this code, but it doesn´t work.

telefo = input(Fore.LIGHTGREEN_EX   "TELEFONO CONTACTO: "   Fore.RESET)
    for x in range(len(telefonos)):
        if(telefonos[x] == telefo):
            print(contactos["telefonos"][x])
        else:
            print("No encontrado")

I print only the telefono value, ´cause it´s my test code.

CodePudding user response:

This should be your working script:

# I imagine your data to be somethig like this. If it isn't, sorry:
id = 0
nombres = ['John', 'Anna', 'Robert']
apellidos = ['J.', 'A.', 'Rob.']
telefonos = ['333-444', '222-111', '555-888']
correos = ['[email protected]', '[email protected]', '[email protected]']

# This is the part where you made it wrong.
# Dictionaries are created with {}
#
# [] creates a list, not a dictionary structure.
#
# Also, key and values must be grouped as:
# "key": value
contactos = dict({
    "id": id,
    "nombres": nombres,
    "apellidos": apellidos,
    "telefonos": telefonos,
    "correos": correos
})

# Now, imagine this this is the input from user:
telefo = "333-444"
for x in range(len(telefonos)):
    if (telefonos[x] == telefo):
        print(contactos["telefonos"][x])
        break
    else:
        print("No encontrado")

When testing the script, the output is 333-444.

  • Related