简体   繁体   English

Python 中的字典和带值的键

[英]Dictionary in Python and key with value

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")

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 ):我认为通过items()方法(或iteritems()如果您使用的是python2 )迭代dict的键和值是一个更好的主意:

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.而且北极熊通常不友好。

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!

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM