-3

I have to create a program which will print a greeting only to friendly bears. I have created this program but it gives me all the bears, the angry ones too.

bears = {"Grizzly":"angry", "Brown":"friendly", "Polar":"friendly"}
for bear in bears:
  if "[bear]:friendly":
   print("Hello, "+bear+" bear!")
else:
  print("odd")
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
Joaquin
  • 1
  • 1

3 Answers3

0

I think it is a better idea to iterate over dict's keys' and values by items() method (or iteritems() if you are using python2):

for bear_name, status in bears.items():  # get key and value for bear
    if status == 'friendly':
        print("Hello, " + bear_name + " bear!")

And polar bears are usually not friendly.

Ivan Vinogradov
  • 4,269
  • 6
  • 29
  • 39
0

You can use this approach :

bears = {"Grizzly":"angry", "Brown":"friendly", "Polar":"friendly"}

for i,j in bears.items():
    if j=="friendly":
        print("Hello, " + i + " bear!")
    else:
        print('odd')

output:

odd
Hello, Polar bear!
Hello, Brown bear!
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88
0

You can use the following, which should give you the output you want:

for bear in bears:
if bears[bear] == "friendly":
    print("Hello, " + bear + " bear!")
else:
    print("odd")
hubble
  • 1
  • 1