Python beginner with a question about a list of dictionaries

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • iriejams
    New Member
    • Feb 2016
    • 1

    Python beginner with a question about a list of dictionaries

    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:

    Code:
    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
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    I would include it in the dictionary rover = {'name':'rover' , 'type': 'dog', 'owner': 'joe'}

    Comment

    • Luk3r
      Contributor
      • Jan 2014
      • 300

      #3
      You could also simply include the item you're iterating.

      Code:
      ...("\nPet Name:", pet, "\nType:", pet['type'].title()...
      I'm not sure if your assignment is suggesting you use one way or the other, but figured I'd point out a second option.

      Comment

      • dwblas
        Recognized Expert Contributor
        • May 2008
        • 626

        #4
        You could also simply include the item you're iterating.

        Code:
        ...("\nPet Name:", pet, "\nType:", pet['type'].title()...
        That would print the entire contents of each dictionary as pets is a list of dictionaries.

        Comment

        Working...