Create dicconario list from iteration in cycle for

0

I come with my second question, I'm just getting started in programming in python.

To the point:

I'm iterating over the data from a list of dictionaries, and I need to create another list of dictionaries with certain data that I select. The new list is already created empty, the dictionaries I want to be added for each iteration.

This is the idea of the code:

lista_dict_vacia = []   

lista_dict_actual = [{'dato1': 'valor1'}, {'dato2': 'valor2'},      
 {'dato3': 'valor3'}, {'dato4': 'valor4'}]

for item in lista_dict_actual:

      if item['dato1'] == item['dato4']:
         enviar el item['dato1'] con su valor a lista_dict_vacia
         enviar el item['dato4'] con su valor a lista_dict_vacia 

De modo que la nueva lista de diccionaios quede así:

lista_dict_vacia = [{'dato1': 'valor1','dato4': 'valor4'}]

I made myself understand? Any help I thank them a million!

    
asked by DDBCDVD 09.08.2018 в 23:13
source

1 answer

0

Gentlemen, I already found the solution, what I did was that for each iteration on the first list of dictionaries, I kept the value of the key in a variable. Then I applied the condition to those variables that already contained the value of the keys. If the condition is met, a dictionary called 'data' is created, where I define the name of the key, and the value of these are the variables that fulfilled the condition . After the iteration on the data ends, I introduce that dictionary into the empty list defined above. Following the code of my question, it was exactly like this:

lista_dict_vacia = [] lista_dict_actual = [{'dato1': 'valor1'}, {'dato2': 'valor2'}, {'dato3': 'valor3'}, {'dato4': 'valor4'} ] for item in lista_dict_actual: variable1 = item['dato1'] variable2 = item['dato4'] if variable1 == variable2: data = {'clave1': variable1, 'clave2': variable2 } lista_dict_vacia.append(data) lista_dict_vacia = [{'clave1': variable1, 'clave2': variable2}]

    
answered by 10.08.2018 / 15:23
source