Python - from Txt File to Dictionary and to Json

Python - from Txt File to Dictionary and to Json

I want to convert a file to json. The file has the format:

Temp=24.0* Humidity=41.0% Date=02/01/17-20:37
Temp=24.0* Humidity=42.0% Date=02/01/17-20:38
Temp=24.0* Humidity=42.0% Date=02/01/17-20:39

I'm using the following code:

list = {}
with open("record.txt") as f:
  for line in f:
    if not ("Failed" in line):
      lists = line.split(" ")
      for l in lists:
        ll = dict([l.split("=")])
        // print(json.dumps(ll))
        list.update(ll)

And when I print the dictionary created i get.

>>> print (list)
{'Temp': '29.0*', 'Humidity': '31.0%', 'Date': '15/07/17-10:56\n', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Temp': '21.0*'}

I don't understand why. Does anyone knows why i don't get the entire dictionary?

Before converting to json i will also separate to sub-dictionary's by new line /n. Is this possible?

1

2 Answers

Your input file contains the same set of unique keys three times so a corresponding representation in Python, which can then be serialised to JSON, is an array of dictionaries.

Try this change to your code: list = [] with open("record.txt") as f: for line in f: if not ("Failed" in line): lists = line.rstrip().split(" ") ll = {} for l in lists: k,v = l.split("=") ll[k] = v list.append(ll)

If you then do: print list

You should get: print list [{'Date': '02/01/17-20:37', 'Temp': '24.0*', 'Humidity': '41.0%'}, {'Date': '02/01/17-20:38', 'Temp': '24.0*', 'Humidity': '42.0%'}, {'Date': '02/01/17-20:39', 'Temp': '24.0*', 'Humidity': '42.0%'}]

You can then dump to JSON with: import json json.dumps(list) '[{"Date": "02/01/17-20:37", "Temp": "24.0*", "Humidity": "41.0%"}, {"Date": "02/01/17-20:38", "Temp": "24.0*", "Humidity": "42.0%"}, {"Date": "02/01/17-20:39", "Temp": "24.0*", "Humidity": "42.0%"}]'

0

You can create a list of dictionaries like this and then can do whatever modification you want to do.

list = {}
complete_list=[]
with open("record.txt") as f:
  for line in f:
    if not ("Failed" in line):
      lists = line.split(" ")
      lists[-1] = lists[-1].strip()       #it should remove the \n at the end.
      for l in lists:
        ll = dict([l.split("=")])
        // print(json.dumps(ll))
        list.update(ll)
        complete_list.append(list)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.