By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,946 Members | 773 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,946 IT Pros & Developers. It's quick & easy.

Python beginner with a question about a list of dictionaries

P: 1
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:

Expand|Select|Wrap|Line Numbers
  1. rover = {'type': 'dog', 'owner': 'joe'}
  2. blackie = {'type': 'cat', 'owner': 'gail'}
  3. polly = {'type': 'bird', 'owner': 'paul'}
  4. seth = {'type': 'snake', 'owner': 'stan'}
  5.  
  6. pets = [rover, blackie, polly, seth]
  7.  
  8. for pet in pets:
  9.     print("\nPet Name:", "\nType:", pet['type'].title(), "\nPet Owner:", pet['owner'].title())
  10.  
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
Feb 24 '16 #1

✓ answered by dwblas

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

Share this Question
Share on Google+
3 Replies


Expert 100+
P: 613
I would include it in the dictionary rover = {'name':'rover', 'type': 'dog', 'owner': 'joe'}
Feb 25 '16 #2

100+
P: 299
You could also simply include the item you're iterating.

Expand|Select|Wrap|Line Numbers
  1. ...("\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.
Feb 25 '16 #3

Expert 100+
P: 613
You could also simply include the item you're iterating.

Expand|Select|Wrap|Line Numbers
  1. ...("\nPet Name:", pet, "\nType:", pet['type'].title()...
That would print the entire contents of each dictionary as pets is a list of dictionaries.
Feb 26 '16 #4

Post your reply

Sign in to post your reply or Sign up for a free account.