Print dict iteration elements as it is read(declared)

47 Views Asked by At

I am reading a dictionary in python2.6 as below I know Python3.6 will read the dictionary in the same order it is declared, but i need to achieve this in Python2.6 (OrderedDict is also not available in Python2.6)

numbermap = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

>>> for k, v in numbermap.iteritems():
...    print(k,v)
...
('four', 4)
('three', 3)
('five', 5)
('two', 2)
('one', 1)

I want the output to be

('one',1)
('two', 2)
('three', 3)
('four', 4)
('five', 5)

I need to write as I read the dictionary. Any ideas to achieve this in Python 2.6?

3

There are 3 best solutions below

2
ukrutt On

It seems that you want an ordered dictionary. If you can use Python 2.7, look up collections.OrderedDict: https://docs.python.org/2/library/collections.html#collections.OrderedDict

If you have to stick with 2.6, there are some suggestions here: https://stackoverflow.com/a/1617087/3061818 (but you should probably head over to Dictionaries: How to keep keys/values in same order as declared?)

1
Adem Öztaş On

There are many practices available for the sorting dictionary. You can check below examples.

First example:

>>> import operator
>>> numbermap = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
>>> sorted_maps = sorted(numbermap.items(), key=operator.itemgetter(1))
>>> print(sorted_maps)
[('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]

Second example:

>>> import collections
>>> sorted_maps = collections.OrderedDict(numbermap)
>>> print(sorted_maps)
OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)])
3
陈海栋 On

1 reverse the key value,

2 sort the new key which is the value

my solution is to sort the keys

sounds like cheating, but works:

first call something to reverse dict

for i in sort(numbermap.keys()):
  print(i,numbermap[i])