Print the name of a dictionary in Python

Asked

Viewed 61 times

2

Follows the code:

layla = {'tipo':'cachorro', 'nome_dono':'lucas'}
ratata = {'tipo':'rato', 'nome_dono': 'Dante'}
pikachu = {'tipo': 'furão', 'nome_dono':'Ash'}

pets = [layla, ratata, pikachu]
for animal in pets:
    print ("Nome do dono:", animal["nome_dono"].title(),"\nEspécie do animal:", animal["tipo"].title(), "\n")

I also need to print the name of the animal, which in turn is the name of the dictionary.

How do I do that?

  • You need to have a key to the animal’s name, no?

1 answer

1

In order for you to write on the screen the value of the animal’s name, you must create a key with the name of each one, so just add the same object to that key. There are several ways to do it. I found this more practical because I could keep your 3 dictionaries with the same value.

layla = {'tipo':'cachorro', 'nome_dono':'lucas'}
ratata = {'tipo':'rato', 'nome_dono': 'Dante'}
pikachu = {'tipo': 'furão', 'nome_dono':'Ash'}

pets = [{"layla":layla}, {"ratata": ratata}, {"pikachu":pikachu}]
for animal in pets:
  nome_animal = ""
  for e in animal:
    nome_animal = e
  print("Nome do animal: "+nome_animal)
  p = animal[nome_animal]
  print ("Nome do dono:", p["nome_dono"].title(),"\nEspécie do animal:", p["tipo"].title(), "\n")

Browser other questions tagged

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