OrderedDict and json loads keep the origin order

2019-10-0308:52:36 Comment

OrderedDict is the sub object of dict, it will remember the origin order of the content. When compare two OrderedDict objects, equal means the two have the same order.

import collections  
d = collections.OrderedDict()  
d[3] = 'A'  
d[2] = 'B'  
d[1] = 'C'  

for k, v in d.items():  
   print k, v  

result:
3 A
2 B
1 C

Use the OrderedDict, json.loads() can keep the origin content order as the OrderedDict objects.

import json  
from collections import OrderedDict  
metadata = json.loads(text, object_pairs_hook=OrderedDict);

The metadata is the OrderedDict object, has the same order of the origin order.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: