2

My assignment is:

Make several dictionaries, where the name of each dictionary is the name of a pet. In each dictionary, include the kind of animal and the owner’s name. Store these dictionaries in a list called pets. Next, loop through your list and as you do print everything you know about each pet.

What I have so far:

rover = {'type': 'dog', 'owner': 'joe'}
blackie = {'type': 'cat', 'owner': 'gail'}
polly = {'type': 'bird', 'owner': 'paul'}
seth = {'type': 'snake', 'owner': 'stan'}

pets = [rover, blackie, polly, seth]

for pet in pets:
    print("\nPet Name:", "\nType:", pet['type'].title(), "\nPet Owner:", pet['owner'].title())

Output so far:

Pet Name: Type: Dog Pet Owner: Joe

Pet Name: Type: Cat Pet Owner: Gail

Pet Name: Type: Bird Pet Owner: Paul

Pet Name: Type: Snake Pet Owner: Stan

My Question:

What do I need to add to my code to have the output include the Pet Name?

Desired Output:

Pet Name: Rover Type: Dog Pet Owner: Joe

Pet Name: Blackie Type: Cat Pet Owner: Gail

Pet Name: Polly Type: Bird Pet Owner: Paul

Pet Name: Seth Type: Snake Pet Owner: Stan

RootFire
  • 119
  • 1
  • 2
  • 11

2 Answers2

7

I would store the name in the dictionary.

rover = {'name' : 'rover', 'type': 'dog', 'owner': 'joe'}
Andrew Jenkins
  • 1,590
  • 13
  • 16
  • I am aware that I could get my desired output that way however it goes against the specifics of what the assignment calls for. Is there a way I can reference the dictionary variable names from the list i have? – RootFire Feb 24 '16 at 23:30
  • 3
    While there may be a way to do this in Python it's not a good idea. I highly doubt that it's what your instructor is looking for. – Andrew Jenkins Feb 24 '16 at 23:33
  • 3
    I agree with @AndrewJenkins. If you're really interested, have a look at the most upvoted answer of http://stackoverflow.com/questions/2553354/how-to-get-a-variable-name-as-a-string-in-python. You could also store your pets in a dictionary {'rover': rover, ...}. How to iterate through them is left as an exercise. – Flavian Hautbois Feb 24 '16 at 23:35
0

You can use an if statement:

for pet in pets:
    for v in pet.values():
        if v == 'joe':
            print("\nPet Name: Rover", "\nType:", pet['type'].title(), "\nPet Owner:", pet['owner'].title())
        if v == 'gail':
            print("\nPet Name: Blackie", "\nType:", pet['type'].title(), "\nPet Owner:", pet['owner'].title())
        if v == 'paul':
            print("\nPet Name: Polly", "\nType:", pet['type'].title(), "\nPet Owner:", pet['owner'].title())
        if v == 'stan':
            print("\nPet Name: Seth", "\nType:", pet['type'].title(), "\nPet Owner:", pet['owner'].title())

Output:

'Pet Name: Rover '
'Type: Dog'
'Pet Owner: Joe'

'Pet Name: Blackie'
'Type: Cat'
'Pet Owner: Gail'

'Pet Name: Polly'
'Type: Bird'
'Pet Owner: Paul'

'Pet Name: Seth'
'Type: Snake'
'Pet Owner: Stan'
Xero Smith
  • 1,968
  • 1
  • 14
  • 19
Klimpason
  • 1
  • 2