0

I'm parsing hl7 to json. I opened the file and created an array where each line is an array like so...

[['MSH', '^~\\&', 'ADM', 'SHM', 'ALL', 'ALL', '20090101010000', 'ORU^R01', 'IHS-20090101010000.00830', 'P', '2.1\n'],
['PID', '1', '9081717170722.97472', 'RUBIE^ALBERT^ALLEN^^^AS', '19930812', 'M', '3250 DEL PASO BLVD^BUTTE^CHICO^CA^95973^USA', '393-41-9499', '393-41-9499\n']]

I created few functions to parse, delete empty elements and so on. At the end of the process, I'm iterating over the matrix and created a dictionary. However, I lose the order of each row in the dictionary...

{'IN1.0': {'IN1.0.0': 'IN1',
       'IN1.0.1': '1',
       'IN1.0.2': 'UNIT HLTH',
       'IN1.0.3': 'RUBIE^ALBERT^ALLEN^^^AS',
       'IN1.0.4': 'SELF'},
'MSH.0': {'MSH.0.0': 'MSH',
       'MSH.0.1': '^~\\&',
       'MSH.0.10': '2.1',
       'MSH.0.2': 'ADM',
       'MSH.0.3': 'SHM',
       'MSH.0.4': 'ALL',
       'MSH.0.5': 'ALL',
       'MSH.0.6': '20090101010000',
       'MSH.0.7': 'ORU^R01',
       'MSH.0.8': 'IHS-20090101010000.00830',
       'MSH.0.9': 'P'},

The MSH should be the first line in the object and it came 2nd. Also notice the MSH.0.1 is followed by MSH.0.10. It looks like the dictionary in Python is sorting the keys by default. If so... How can I keep the order as FIFO?

Ry-
  • 218,210
  • 55
  • 464
  • 476
redeemefy
  • 4,521
  • 6
  • 36
  • 51
  • 1
    `dict`s aren’t ordered; use an [`OrderedDict`](https://docs.python.org/3/library/collections.html#collections.OrderedDict). – Ry- Mar 12 '17 at 03:07
  • if all the keys are just `MSH.0.X` why not just use a list where `X` is the indice? – Tadhg McDonald-Jensen Mar 12 '17 at 03:11
  • `OrderDict()` changes the structure of the dictionary. Now it is a bid tuple with nested arrays with nested tuples. However, the order that is coming from the original hl7 is preserved. – redeemefy Mar 12 '17 at 03:16
  • 1
    @Gilbert It didn't change the format, just the output. try using `json.dumps(data, indent=2)` for printing purposes (assuming everything in the structure is suited for json. – Tadhg McDonald-Jensen Mar 12 '17 at 03:20
  • Yep, I `print(json.dumps(data, indent=3)) and got the expected result. – redeemefy Mar 12 '17 at 03:27

0 Answers0