Retain Python2 dictionary iteration order in Python3

86 Views Asked by At

I am porting some code from python 2 to 3.

data = {'direction': '->', 'src_port': 'any', 'src_ip': 'any', 'dst_port': 'any', 'dst_ip': 'any', 'action': 'alert', 'protocol': 'http'}

Iterating the above dictionary in python 2

>>> for k, v in data.iteritems():
...     print(k, v)
... 
('direction', '->')
('src_port', 'any')
('protocol', 'http')
('src_ip', 'any')
('dst_port', 'any')
('action', 'alert')
('dst_ip', 'any')

Iterating the above dictionary in python 3 (insertion order is maintained)

>>> for k,v in data.items():
...     print(k, v)
... 
direction ->
src_port any
src_ip any
dst_port any
dst_ip any
action alert
protocol http

Is there any way by which I can retain the python2 dictionary iteration order in python3?

0

There are 0 best solutions below