Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get a value of a dictionary within a list of dictionaries when the dict equals a certain name?

I want to retrieve certain values from a list object that contains strings and dictionaries. If the dictionary equals a certain name I want to add it to the output file.

First I read in a json file which looks like this:

    {
      "event": "user",
      "timestamp": {
        "$numberDouble": "1671459681.4369426"
      },
      "metadata": {
        "model_id": "125817626"
      },
      "text": "hello",
      "parse_data": {
        "intent": {
          "name": "greet",
          "confidence": {
            "$numberDouble": "1.0"
          }
        },

I have events that equal "user" and those that equal "bot". What I want to have in the end is an output file that has user and bot in each line. At the beginning of the line I also want to have the timestamp, formatted in human readable time, and at the end the text like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2020-03-13 12:11:25 user: hello

2020-03-13 12:11:28 bot: Hi

However, I do not know how to access the value of "timestamp", format it and then print it together with "user" and "text" in one line.

What I have done so far is that:

     import json
     from datetime import datetime

     f = open('1234.json')
  
     data = json.load(f)
     all_events = [e for e in data.get('events', list()) if e.get('event')=='user' or e.get('event')=='bot']

     file_object = open('1234.txt', 'a')
     for event in all_events:
         file_object.write(str(event.get('timestamp'))+ " "+ event.get('event')+ ": " + event.get('text', '')+ "\n")

     f.close()

What I get with this is:

{‘$numberDouble’: ‘1671459681.4369426’} user: hello

I know that I can use something like this to format the time

      ts = int("1584101485")
      print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

But I do not know how to wrap this in my file_object.write command

>Solution :

Instead of getting the timestamp key’s value, you need to parse the $numberDouble value inside of the timestamp dictionary:

file_object.write(
    datetime.utcfromtimestamp(float(event['timestamp']['$numberDouble'])).strftime('%Y-%m-%d %H:%M:%S') + " "+ event.get('event')+ ": " + event.get('text', '')+ "\n"
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading