Home > OS >  From DataFrame to particular json format
From DataFrame to particular json format

Time:10-29

I would like to convert this DataFrame (as dict):

{'bisac_code1': {2: {'BIO016000': 0.8,
   'CKB041000': 0.30000000000000004}},
 'bisac_code2': {2: {'CKB049000': 0.3,
   'BIO028000': 0.8}},
 'bisac_code3': {2: {'SPO058000': 0.8,
   'CKB030000': 0.3}}}

to this json_format:

"bisac_code_1": { [
    {"code": …
    "weight": ….
   },
    {"code": …
    "weight": ….
   }
]
},
"bisac_code_2": {
[
    {"code": …
    "weight": ….
   },
    {"code": …
    "weight": ….
   }
]
},
"bisac_code_3": {
[
    {"code": …
    "weight": ….
   },
    {"code": …
    "weight": ….
   }
]

I could solve it, but in a not very pythonic way (some for loops and a lot of string format). Is there any nice way to do it?

CodePudding user response:

Not sure what's unpythonic of using a loop? a defaultdict from the collections lib and you're good to go.

assuming your dict is called d

from collections import defaultdict
import json

target_ = defaultdict(list)

for code, vals in d.items():
    for _,items in vals.items():
        for each_item in items.items():
            target_[code].append(dict(zip(['code','weight'], each_item)))


print(json.dumps(target_, indent=1))

{
 "bisac_code1": [
  {
   "code": "BIO016000",
   "weight": 0.8
  },
  {
   "code": "CKB041000",
   "weight": 0.30000000000000004
  }
 ],
 "bisac_code2": [
  {
   "code": "CKB049000",
   "weight": 0.3
  },
  {
   "code": "BIO028000",
   "weight": 0.8
  }
 ],
 "bisac_code3": [
  {
   "code": "SPO058000",
   "weight": 0.8
  },
  {
   "code": "CKB030000",
   "weight": 0.3
  }
 ]
}

   
  • Related