简体   繁体   English

Python 字典问题 - 每次运行时 output 不同(使用字典输入,列表工作正常)?

[英]Python dictionary issue- different output with each run (with dictionary input, works fine with a list)?

I'm new to python (and stackoverflow) and have written this short piece of code which declares "suitable for vegetarians" depending on the values of the dictionary, or "not suitable for vegetarians" should something non-veggie be encountered (ie bacon).我是 python(和 stackoverflow)的新手,并编写了这段简短的代码,根据字典的值声明“适合素食者”,或者如果遇到非素食者(即培根),则“不适合素食者” )。 I've included a print statement after break to test that break works correctly, so that when bacon is encountered, the for loop stops and 'else' is also inhibited.我在 break 之后包含了一个 print 语句来测试 break 是否正常工作,因此当遇到 bacon 时,for 循环停止并且“else”也被禁止。 My issue is that each time I build and run this code in Sublime, I get a different output.我的问题是,每次我在 Sublime 中构建和运行这段代码时,都会得到不同的 output。 When running it on the Codecademy online IDE, depending on the key for "mushrooms", it will either print this inappropriately (say with key "3") or will not print (as expected) with key "4".在 Codecademy 在线 IDE 上运行它时,根据“蘑菇”的键,它会不恰当地打印(比如使用键“3”)或不会使用键“4”打印(如预期的那样)。 I've changed the dictionary to a list and the code functions correctly, but this issue persists when using a dictionary- I can't figure out the reason for this, so any help would be great!我已将字典更改为列表并且代码正常运行,但使用字典时此问题仍然存在 - 我无法找出原因,所以任何帮助都会很棒!

breakfast = {"1": "eggs", "2": "bacon", "3": "mushrooms", "4": "bread", "5": "tomatoes"}

for item in breakfast:
  if breakfast[item] == "bacon":
    print ("Not suitable for vegetarians")
    break
  print (item, breakfast[item])
else:
  print ("Suitable for vegetarians!")

Dictionaries in Python are unordered when using Python <= 3.5 Python 中的字典在使用 Python <= 3.5 时是无序的
That means you arent guaranteed to get they keys in any particular order when you loop over them.这意味着当您遍历它们时,您不能保证以任何特定的顺序获取它们的密钥。

What Python version are you using?您使用的是什么 Python 版本?

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

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