0

I have a dictionary like below, i want to create a a dataframe but only from result key(i.e a list of dictionary)

dict =  {
 'ID': 'c2a4da4e3',
 'Time': None,
 'recordsReturned': 5,
'TotalRecord': 512,
'result': '[{"Time":"2022-03-04T14:39:59.999Z","metric":"dpmo","value":15}, 
          {"Time":"022-03-04T14:39:59.999Z" ","metric":"Load Balancing","value":1}, 
         {"Time":"2022-03-04T14:39:59.999Z","metric":"High Defect","value":13},
          {"Time":"2022-03-04T14:39:59.999Z","metric":"Low Defect","value":121},
         {"Time":"2022-03-04T14:39:59.999Z","metric":"Successful ","value":306}]',
        'Token': None
  }  

I want something like below.

df = Time                        metric           value
     2022-03-04T14:39:59.999Z     dpmo             15
     022-03-04T14:39:59.999Z      Load Balancing   1

i tried this but gives me an empty list of values

print(([key for key in raw.keys()][4], [value for value in raw.values()][4]))
Learner
  • 335
  • 3
  • 16
  • Why do you expect that `print(...)` statement to create a dataframe? – Pranav Hosangadi Mar 04 '22 at 15:33
  • Your `result` key is a _json string_, not a list of dictionaries. Sure, it _represents_ a list of dicts, but you still need to parse it into one before doing anything with it. Check out the docs for the `json` module. Do you see something there that can parse a json string to an object for you? – Pranav Hosangadi Mar 04 '22 at 15:35
  • And once you have an actual list of dicts, a quick google search yields a stackoverflow link that answers your question. [Convert list of dictionaries to a pandas DataFrame](https://stackoverflow.com/questions/20638006/convert-list-of-dictionaries-to-a-pandas-dataframe) – Pranav Hosangadi Mar 04 '22 at 15:36
  • print was just to test. i want to create a dataframe – Learner Mar 04 '22 at 15:44
  • i used this code to get the dict dict = json.loads(resp.text).......i believe its already parsed here – Learner Mar 04 '22 at 15:51
  • Okay, you parsed the `resp.text` to a dict. But the `result` key of that dict is _still a string, isn't it?_ Use the same `json.loads()` to convert that string to an actual list of dicts. Then see the question Ilinked. – Pranav Hosangadi Mar 04 '22 at 16:04
  • hmm.ok got it. It works now. i used result = json.loads(dict['result']) and created a dataframe df = pd.DataFrame(result). Gives me exactly what i want. Thanks – Learner Mar 04 '22 at 16:13

0 Answers0