Compare Python index independent lists

Asked

Viewed 135 times

0

Good afternoon,

I need to compare 2 lists and when a certain value in the 'name' field of the list 1 does not exist in the 'name' field of the list 2 perform some function.

The way I did is comparing index by index and running if every time the fields are different, but in case I want to run only when there is no value in any list 2 Dice

dados1 = [{'name': 'Polo Pedreira', 'id': '02'},
            {'name': 'Polo Itu', 'id': '01'}]

dados2 = [{'name': 'Polo Jaguariuna', 'id': '03'},
           {'name': 'Polo Itu', 'id': '04'}]

for dadost1 in dados1:
    for dadost2 in dados2:
        if dadost1['name'] != dadost2['name']:
            print(dadost2)

He’s returning it to me:

{'name': 'Polo Jaguariuna', 'id': '03'} {'name': 'Polo Itu', 'id': '04'} {'name': 'Polo Jaguariuna', 'id': '03'}

Thanks in advance

2 answers

3

I thought of the following solution:

1) Take names as a list of names

def pega_nomes_de_dicionario(lista):
    lista_nomes=[]
    for dic in lista:
        lista_nomes.append(dic['name'])
    return lista_nomes

>>> nomes_dados1 = pega_nomes_de_dicionario(dados1)
>>> nomes_dados2 = pega_nomes_de_dicionario(dados2)
>>> print nomes_dados1
['Polo Pedreira', 'Polo Itu']

2) check which names only have on one list and not on the other

def pega_nomes_fatantes(nomes_dados1, nomes_dados2):
    nomes_faltantes = []

    for nome in nomes_dados1:
        if nome not in nomes_dados2:
            nomes_faltantes.append(nome)

    return nomes_faltantes

>>>> nomes_faltantes = pega_nomes_fatantes(nomes_dados1, nomes_dados2)
>>>> print nomes_faltantes
['Polo Pedreira']

3) Take the full data of the missing names

def pega_dado_completo(nomes_faltantes, dados1, dados2):
    for dado in dados1:
        if dado['name'] in nomes_faltantes:
            print(dado)

>>> pega_dado_completo(nomes_faltantes, dados1, dados2)
{'name': 'Polo Pedreira', 'id': '02'}
  • 1

    Good evening Alex, I took your thought as a basis and wrote my code again, remaking it as objective as possible.

2


Taking as a basis the thought of Alex, redo my code:

listaNomes=[]
for nome in dados2:
    listaNomes.append(nome['name'])

for dadost1 in dados1:
    if dadost1['name'] not in listaNomes:
        print(dadost1)

Returned me the only given in the first non-existent list in the second list:

{'name': 'Polo Pedreira', 'id': '02'}

  • 1

    I’m glad my code helped, but yours is much better hahaha

  • mark yours as the right answer then

  • I thought I could not do this, thanks for warning hahaha. Obs: I tried here but he only lets me do this tomorrow.

Browser other questions tagged

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