繁体   English   中英

在python中循环浏览字典

[英]Looping through dictionary in python

在此处输入图片说明

随附的是我要回答的问题的副本。 (顺便说一句,这不是一本家庭作业,只是来自一本编程电子书)。

因此,我首先创建了字典。

fridge ={ "steak" : "it is so yum!" , \
  "Pizza" : "it is even yummier!" , \
  "eggs": "always handy in a pinch" , \
  "ice cream": "a tasty treat for when I work hard" , \
  "butter" : "always useful for spreading on toast" \
  }

必须承认,也许这是用句子来表达文字的方式:

然后创建一个名称,该名称引用包含食品名称的字符串,将名称命名为food_sought

令我非常困惑。

我认为这意味着:

创建一个名为food_sought的变量,使其等于冰箱词典中的任何键。...然后使用for循环查看词典中是否存在匹配项。

所以....

    food_sought = "steak"
for food_sought in fridge:
    if food_sought !=steak:
        print ("there has not been a match!")

但是,每当我运行代码时,都会被告知:

追溯(最近一次呼叫最近):文件“”,第2行,如果food_sought == steak:NameError:未定义名称“ steak”

在这种情况下, steak将是一个变量。

您所要求的是:

food_sought != 'steak'

但是你可能想要的是

key != food_sought

见下文

如果需要该值,则可以在python3中使用items()或在python 2中使用iteritems()

food_sought = 'steak'
for key, value in fridge.items():
    if key != food_sought:
        print("Not the key we're looking for...")
    print(key)    # the key, ie "steak'
    print(value)  # the value, ie "it is so yum!" -- I agree

牛肉,这是晚餐。

这是您可以使用for循环遍历字典的方式,希望它可以帮助您更好地理解:)

fridge ={ "steak" : "it is so yum!" , \
  "Pizza" : "it is even yummier!" , \
  "eggs": "always handy in a pinch" , \
  "ice cream": "a tasty treat for when I work hard" , \
  "butter" : "always useful for spreading on toast" \
  }

food_sought = "steak"

for key, value in fridge.items():
  if(key == food_sought):
    print(key, 'corresponds to', value)
  else:
    print ("There has not been a match!")

输出:(注意字典未排序)

There has not been a match!
There has not been a match!
There has not been a match!
There has not been a match!
steak corresponds to it is so yum!

在这里尝试

问题在于,牛排是一个尚未定义的变量。 当您编写food_sought!=steak您正在比较两个变量的值,但是未定义变量牛排

您的第一行代码错误地分配了food_sought="steak" ,应该分配了food_sought="steak" steak='steak' 这样,您的代码将起作用:

steak = "steak"
for food_sought in fridge:
    if food_sought != steak:
        print ("there has not been a match!")

话虽这么说,虽然可以工作,但您编写代码的方式并不是最好/最好的方法。 没有必要定义变量的steak ,你可以比较food_sought变量直接对字符串'steak' 代码如下所示:

for food_sought in fridge:
    if food_sought != 'steak':
        print ("there has not been a match!")

暂无
暂无

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

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