Lists of dictionaries

Asked

Viewed 913 times

0

I have a list of dictionaries like the following and I want to get for a list the ages of the animals of each owner, for example, the animals of ana have on average x years ... However I am not getting the ages of the animals related to their owners, someone can give a help ?

lista1 =[
{'Idade': '8','Especie': 'Gato', 'Nome do Animal': 'Felix'},
{'Idade': '57','Especie': 'Tartaruga','Nome do Animal': 'Michelangelo'},
{'Idade': '12','Especie': 'Cao', 'Nome do Animal': 'Rantanplian'},
{'Idade': '2','Especie': 'Peixe', 'Nome do Animal': 'Nemo'},
{'Idade': '45','Especie': 'Tartaruga','Nome do Animal': 'Leonardo'},
{'Idade': '9','Especie': 'Cao', 'Nome do Animal': 'Milo'},
{'Idade': '57','Especie': 'Tartaruga','Nome do Animal': 'Raphael'},
{'Idade': '4','Especie': 'Peixe', 'Nome do Animal': 'Dory'}]

lista2 =[
{'Nome do Dono ': 'Ana','Nome do Animal': 'Michelangelo'},
{'Nome do Dono ': 'Eva','Nome do Animal': 'Dory'},
{'Nome do Dono ': 'Ada','Nome do Animal': 'Rantanplan'},
{'Nome do Dono ': 'Ana','Nome do Animal': 'Leonardo'},
{'Nome do Dono ': 'Eva','Nome do Animal': 'Felix'},
{'Nome do Dono ': 'Ana','Nome do Animal': 'Raphael'},
{'Nome do Dono ': 'Eva','Nome do Animal': 'Nemo'}]`

The problem is that I can’t use input’s or anything like that and the code has to work for some list that I put on top of it is just an example. What I have to get ( in this example) is :

[{'Ana':'53','Eva':'5','Ada':'12'}]

But first I need to put the ages of each owner’s animals on a list and then average that’s what I’m not getting. And as far as space is concerned, thank you.

  • Did you duplicate that question here? http://answall.com/questions/124946/how-to-get-the-value-of-a-one-dictionaries-list-depending-on-information-from-an

1 answer

0

In Lista2 the first courses Nome do Dono has space, this can disturb the time of consultation.

Try using this code snippet

item = int(input("Numero da pessoa: "))

animal = lista2[item-1]['Nome do Animal']

for x in range(len(lista1)):
    if animal in lista1[x]['Nome do Animal']:
        print "Idade:", lista1[x]['Idade']
        print "Especie:", lista1[x]['Especie']
        print "Nome:", lista1[x]['Nome do Animal']
        print "Dono:", lista2[item]['Nome do Dono']

Browser other questions tagged

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