Is it possible to use dictionaries within lists in Python?

5

I need to go through a list that contains dictionaries and display the information for it. But testing here the attributes .item() and .value() could not. See:

#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')) ???
    
asked by anonymous 20.11.2018 / 18:06

2 answers

5

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

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, read in the python documentation on Nested Dictionary

    
20.11.2018 / 18:27
5

Starting with Python version 3.6, you can use dataclasses to structure this type of data. Here's 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)
    
20.11.2018 / 19:01