Python dictionary print problem

0 Cardinal Coog · October 21, 2015
Hi All,

New to Python, please bare with me.... The dictionary prints the correct Keys and Values but not in the correct order. Will someone please explain why?

Thanks:

Here's the code:


import random
import sys
import os
import time

print("\nDate:", time.strftime("%y-%m-%d"))
print("Time:", time.strftime("%H:%M"))

dictionary = {'a':'alpha', 'b':'beta', 'c':'chi', 'd':'delta', 'e':'epsilon', 'f':'phi', 'g':'gamma', 'h':'eta',
'i':'iota', 'k':'kappa', 'l':'lambda', 'm':'mu', 'n':'nu', 'o':'omicron', 'p':'pi', 'q':'theta',
'r':'rho', 's':'sigma', 't':'tau', 'u':'upsilon', 'w':'omega', 'x':'xi', 'y':'psi', 'z':'zeta'}
print('\nEnglish', '**********', 'Greek\n')

for k, v in dictionary.items():
print(k + ' ' + v)

Post a Reply

Replies

Oldest  Newest  Rating
0 Dol Lod · October 22, 2015
http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops-in-python says that this method actually iterates in no particular order.

Suggestion:

Get all the keys and store them in an object. Sort the keys. Then use a for loop to print it out.
0 Cardinal Coog · October 22, 2015
Thank you both - .r3d and Dol Lod - for your insightful replies.

I agree that using a list would be better (more efficient and cleaner). The only reason I chose to use a dictionary was because I'm new to Python and wanted to practice the concept/syntax etc.

Thanks again. 
  • 1

Python

107,067 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator