Elodin86
Elodin86

Reputation: 35

How to iterate over values of values in a dictionary?

I have a few dictionaries that I added into one larger dictionary.

violet = {"animal":"cat","owner":"Theresa"}
lucy = {"animal":"cat","owner":"Theresa"}
button = {"animal":"rabbit","owner":"Theresa"}
our_animals = {}
our_animals["Violet"] = violet
our_animals["Lucy"] = lucy
our_animals["Button"] = button
for animal in our_animals:
        print(animal,"is a:")
        for kind, owner in our_animals.values():
            print(kind,"owned by", owner)

This just gave me this

Violet is a:
animal owned by owner
animal owned by owner
animal owned by owner
Lucy is a:
animal owned by owner
animal owned by owner
animal owned by owner
Button is a:
animal owned by owner
animal owned by owner
animal owned by owner

In my mind I've now created a dictionary in which

"Violet" is a key and the dictionary {"animal":"cat,"owner":"Theresa"} is the value associated with "Violet". In the code above I was attempting to iterate over the values of the dictionary which is itself a value. I wanted my output to be something like.

Violet is a:
cat owned by Theresa
Lucy is a:
cat owned by Theresa
Button is a:
rabbit owned by Theresa

I'm only a month into learning python so any teaching moment would be greatly appreciated. Thank you in advance!

Upvotes: 0

Views: 76

Answers (4)

chidalu okechukwu
chidalu okechukwu

Reputation: 27

Do something like this

for key,value in our_animals.items():

  print(str(key)+' is a : ');

  print(str(value['animal'])+' owned by '+str(value['owner']));

Upvotes: 0

PacketLoss
PacketLoss

Reputation: 5746

You can change your first loop to iterate over key,value pairs and then access the owner and animal type via value['animal'] & value['owner'].

for animal_name, animal_data in our_animals.items():
    print(animal_name, 'is a:')
    print(animal_data['animal'], 'owned by', animal_data['owner'])

Using dict.items() to iterate over your key and value pairs here would be the best approach.

Looping Dictionaries

Output:

Violet is a:
cat owned by Theresa
Lucy is a:
cat owned by Theresa
Button is a:
rabbit owned by Theresa

Upvotes: 2

Afif Al Mamun
Afif Al Mamun

Reputation: 199

You can use something like this -

for key, values in zip(our_animals.keys(), our_animals.values()):
        print(key,"is a:")
        print(values["animal"],"owned by", values["owner"])

Upvotes: 0

Maran Sowthri
Maran Sowthri

Reputation: 878

Try this,

violet = {"animal":"cat","owner":"Theresa"}
lucy = {"animal":"cat","owner":"Theresa"}
button = {"animal":"rabbit","owner":"Theresa"}
our_animals = {}
our_animals["Violet"] = violet
our_animals["Lucy"] = lucy
our_animals["Button"] = button
for animal in our_animals:
   print(animal,"is a:")
   print(our_animals[animal]['animal'],"owned by", our_animals[animal]['owner'])

Upvotes: 1

Related Questions