Filter list of python objects

Asked

Viewed 241 times

1

Hello, I’m new to Python and I’m having doubts to filter an object from a list.

I have the following list:

[{ ID: 1, Name: 'Teste 1' }, { ID: 2, Name: 'Teste 2' }]

And I am wanting to realize a filter whose ID is igua; a 1.

I found on the internet a way to filter that’s not working that’s this:

filter(None, lista)

How can I get this filter? Thanks in advance for your attention.

4 answers

2

first create a loop that observes all objects within the list

for i in lista:

then test if the ID property is equal to the desired value (1 for ex.)

if i.ID == 1:

then edit the name of this object for "test" for example.

i.Name = "teste"

complete code:

 for i in lista:
    if i.ID == 1:
        i.Name = "teste"
  • 2

    Welcome to the community! Although your answer is correct, it is desirable to have the explanation of porquê of your solution, so that the answer becomes more complete and serves as a reference for other people.

  • OK, sorry I’ll rewrite the answer

2


The built-in function filter(function, iterable) is defined as such in the language manual:

filter(function, iterable)
Build a iterator from the elements of everlasting for which
Function returns true. The everlasting can be a sequence, a container that supports iteration, or an iterator. If Function is None, the function
identity will be used, that is, all elements of the everlasting that are false are removed.
Note that filter(function, iteravel) is equivalent to the generating expression:

  • (item for item in iteravel if function(item)) if Function is not None.
  • (item for item in iteravel if item) if Function is None.

So when did filter(None, lista) you informed the interpreter that you would like to get the generator (item for item in lista if item) that reality does not filter the lista only produces the generator that reiterates on its items.

To perform the filtering it is necessary to pass a comparative function, as argument in the first parameter. This should return a boolean where:

  • True informs that the item will be accepted by the filter.
  • False informs that the item will be rejected by the filter.

As a filter a anonymous function.

Example: In a list of 100 dictionaries {"ID":inteiro , "Name": string} whose the IDs range from 1 to 100, print only dictionaries whose ID <= 10 and that ID be equal.

#Cria uma lista com dicionários cujo os ids vão de 1 até 100.
entrada =[{"ID": i + 1, "Name": f"Teste{i + 1}"} for i in range(100)]

#Cria o filtro que só retorna True se o ID de x for menor que 10 e a mesmo tempo o ID seja par.
filtro = lambda x: x["ID"] <= 10 and x["ID"] % 2 == 0

#Filtra a lista entrada.
filtrados = list(filter(filtro , entrada))

#Imprime o resultado.
print(filtrados)

This example will result in:

[{'ID': 2, 'Name': 'Teste2'}, 
 {'ID': 4, 'Name': 'Teste4'}, 
 {'ID': 6, 'Name': 'Teste6'}, 
 {'ID': 8, 'Name': 'Teste8'}, 
 {'ID': 10, 'Name': 'Teste10'}]

Returning to the example of the question where you want to perform an element filtering whose ID is equal to 1:

entrada =[{"ID": i + 1, "Name": f"Teste{i + 1}"} for i in range(100)]
    
#Filtro para aceitar apenas o x cujo o ID é um.
filtro = lambda x: x["ID"] == 1
    
filtrados = list(filter(filtro , entrada))


print(filtrados)

What returns:

[{'ID': 1, 'Name': 'Teste1'}]

1

The function filter() applies a function to an eternal object.

In your case, we’d have something like this:

def filtro(x):
    if x['ID'] == 1:
        return True
    else:
        return False

lista = [{ ID: 1, Name: 'Teste 1' }, { ID: 2, Name: 'Teste 2' }]

resultado = filter(filtro, lista)

for _ in resultado:
    print(_)

{'ID': 1, 'Name': 'Teste 1'}

1

You can use the lambda expression and test if the ID is 1

lista = [{'ID': 1, 'Name': 'Teste 1' }, {'ID': 2, 'Name': 'Teste 2' }]

filtrado = filter(lambda x: x['ID'] == 1, lista)

Exit

[f for f in filtrado]
[{'ID': 1, 'Name': 'Teste 1'}]

Browser other questions tagged

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