Access dictionary within a Python list

Asked

Viewed 4,459 times

2

I have the following list whose elements are dictionaries:

[{'nome': 'ana', 'cpf': '1000', 'endereco': 'rua xxxx'}, {'nome': 'carlos', 'cpf': '7770', 'endereco': 'Rua aaaa'}]

I want to do the search by people’s name and name

nome = input("Digite o nome que deseja buscar: ")
     for i in range(0, len(cl_cadastrados)):
        cl = cl_cadastrados[i]

        if (nome == cl['nome']):
            ...
            ...

Is there any simpler way to perform this algorithm? There is some way to access a dictionary inside the list directly without using an auxiliary variable as I am doing. Still getting familiar with Python I’m more used to programming in C.

5 answers

4


The solutions of the other answers always use a for to search the data sequentially, going through all the records. I will offer here two alternative solutions:

The first can only be used if the list is already sorted by name - She searches using a binary tree, which means she splits the list in two until she finds the person she’s looking for. Very efficient with many people, and can be used to find the position where you should insert another person without losing the sort of list, simply pass a name that does not exist:

nomes = [d['nome'] for d in pessoas]

nome_procurado = 'maria'
n = bisect.bisect_left(nomes, nome_procurado) 
print(pessoas[n])

The second way is indexing - you use the for a single time to create a new dictionary whose key is the name, then just use this dictionary to get to the data as many times as you want. This way is better when you will search for many names, because searching in the dictionary after indexed has virtually no cost:

indice_pessoas_por_nome = {d['nome']: d for d in pessoas}

nome_procurado = 'maria'
print(indice_pessoas_por_nome[nome_procurado])

Both solutions can be used also for CPF or any other field.

2

You can use list comprehension if you want to simplify:

pessoas = [{'nome': 'ana', 'cpf': '1000', 'endereco': 'rua xxxx'},
           {'nome': 'carlos', 'cpf': '8770', 'endereco': 'Rua aaaa'},
           {'nome': 'maria', 'cpf': '7770', 'endereco': 'Rua bbbb'}]

nome = 'maria'
cpf = '1000'

encontrados = [p for p in pessoas if p['nome'] == nome or p['cpf'] == cpf]

1

You can iterate over the list elements as follows:

for elm in cl_cadastrados:
    if nome == elm['nome']:
        ...

This way you iterate on the elements of cl_cadastrados and access the elements directly. It’s simpler from the point of view of code size and using python resources, avoiding iterating over indexes and accessing elements in a more optimized way.

1

You can use next()

pessoas = [{'nome': 'ana', 'cpf': '1000', 'endereco': 'rua xxxx'}, {'nome': 'carlos', 'cpf': '7770', 'endereco': 'Rua aaaa'}]
nome = 'carlos'

pessoa = next((p for p in pessoas if p['nome'] == nome), None)
print(pessoa)

-1

Simple!

    pessoas = [{'nome': 'ana', 'cpf': '1000', 'endereco': 'rua xxxx'}, 
{'nome': 'carlos', 'cpf': '7770', 'endereco': 'Rua aaaa'}]

Suppose you want to access only the 'name':

print(pessoas[0]['nome'])

Browser other questions tagged

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