Is it possible to use dictionaries inside lists in Python?

Asked

Viewed 502 times

5

I need to scroll through a list that contains dictionaries and present the information of this one. But testing the attributes here .item() and .value() I couldn’t. Look:

#6.8 - Animais de Estimação:

Pets = [{'Zeus':{'Tipo':'Gato','Dona':'Luciene'},'Jake':{'Tipo':'Dogão',
                    'Dona':'Ide'},'Bob':{'Tipo':'Cachorro','Dono':'Dartinho'}
    }]

for info in Pets.items: #Classe ITEMS só funciona P\ Dic e não Para Listas :/
    print(Pets('Zeus')) ???

2 answers

6

In your case you would have to go through your list and then the dictionary. Since one is inside the other. In fact the method items() does not work in lists, but there is even the need to have a list ? why not a dictionary within another ? for that :

Pets = {'Zeus':{'Tipo':'Gato','Dona':'Luciene'},'Jake':{'Tipo':'Dogão',
                'Dona':'Ide'},'Bob':{'Tipo':'Cachorro','Dono':'Dartinho'}
}

for nome, dado in Pets.items():
    print ("\n Nome: ", nome)

    for key in dado:
        print(dado, dado[key])

Exit:

 Nome:  Zeus
{'Dona': 'Luciene', 'Tipo': 'Gato'} Luciene
{'Dona': 'Luciene', 'Tipo': 'Gato'} Gato

 Nome:  Bob
{'Tipo': 'Cachorro', 'Dono': 'Dartinho'} Cachorro
{'Tipo': 'Cachorro', 'Dono': 'Dartinho'} Dartinho

 Nome:  Jake
{'Dona': 'Ide', 'Tipo': 'Dogão'} Ide
{'Dona': 'Ide', 'Tipo': 'Dogão'} Dogão

For more information on a read in the python documentation on Nested Dictionary

  • 1

    The limitation, in this case, is not being able to have two pets with the same name.

  • Cool! Solved here, I used a Dictionary inside another. Thank you. How do I enjoy the answer ?? ^^

  • 1

    @Namelessman There is no "like" here. But you can accept the answer if you think it was helpful and solved your problem - see how to do it reading the FAQ. And when you have more than 15 points on the site, will also be able vote on posts that find useful. Remembering that here the votes are not like the likes of facebook or other social networks, they have a different meaning

  • 1

    @hkotsubo well placed

6

Starting with Python version 3.6, you can use dataclasses to structure this type of data. See an example:

from dataclasses import dataclass

@dataclass
class Pet:
    nome: str
    tipo: str
    dono: str

pets = [
    Pet(nome='Zeus', tipo='gato', dono='Luciene'),
    Pet(nome='Jake', tipo='dogão', dono='Ide'),
    Pet(nome='Bob', tipo='cachorro', dono='Dartinho')
]

for pet in pets:
    print(pet.nome)

Browser other questions tagged

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