pythondictionaryfor-else

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 (i.e. bacon). 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. My issue is that each time I build and run this code in Sublime, I get a different 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". 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!")

Solution

  • Dictionaries in Python are unordered when using 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?