0

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?

Priyank Chheda
  • 521
  • 5
  • 16
  • 1
    in python2 dictionaries were unordered (or rather arbitrarily ordered) with python3 it keeps the same order that the keys were inserted in ... so just add the keys in the order you want back – Joran Beasley Nov 20 '21 at 07:03
  • 1
    To expand on the above, the good news is that your python 2 code worked as you wanted **by chance**, with python 3 you can make it work reproducibly like you want ;) – mozway Nov 20 '21 at 07:06
  • And if you're always using the same order, a list might be preferred – mozway Nov 20 '21 at 07:08
  • Unfortunately, I can't use a list or any other external sorting mechanism. We use this iteration in MD5 calculation (and hence order is important). And yes, this is a buggy code, but it is in production, and the database is populated with these values. – Priyank Chheda Nov 20 '21 at 07:13
  • If you know that you want the output to be as it was in Python 2 then why not generate the list in Python 3 with the keys in the order you need? –  Nov 20 '21 at 07:23
  • I don't know how python2 generates dictionary iteration order – Priyank Chheda Nov 20 '21 at 07:25
  • If the order is important, that mean you know the order. If you know the order, then you can iterate over the keys in order. Some variation of: `[(key,data[key]) for key in ['direction', 'src_port', 'protocol', 'src_ip', 'dst_port', 'action', 'dst_ip']]` – Mark Nov 20 '21 at 07:32
  • 1
    But you **must** know how the dictionary gets populated! Also, as @Mark says, if you know the order in which you need to observe the keys then just do explicit *get()* rather than iterating over the dictionary. Also, you asked this same question yesterday and got a lot of helpful responses. I'm surprised you've decided to regurgitate it. –  Nov 20 '21 at 07:39
  • @PriyankChheda In Python 2, it is an implementation detail, that probably depends on the exact version – juanpa.arrivillaga Nov 20 '21 at 07:54

0 Answers0