Home > Blockchain >  Remove a Character From a Dictionary with Python
Remove a Character From a Dictionary with Python

Time:10-02

I currently have a .txt file which has the below...

"serial": 1300008948, "material": 649010, "siteID": 23, "locCode": 2136276, "timestamp": 2021/09/29T14:05:16

there can also be multiple lines in this file which all be formatted the same.

I'm taking the text above from the txt file and putting it into a dictionary but my output is like below...

{'serial': '1300008948, "material": 649010, "siteID": 23, "locCode": 2136276, "timestamp": 2021/09/29T14:05:16'}

my code is adding the character ' at the beginning and end of the output.

I would like the remove the ' if possible?

My code is below...

filename = 'offline_q.txt'
dict1 = {}
tag = "serial"
with open(filename) as f:
     for line in f:
     key, desc = line.strip().split(None, 1)
     dict1[tag] = desc.strip()
     print(dict1)
     x = requests.put(send_data_url, headers=headers, json=dict1)
     print(x)

CodePudding user response:

You could've used eval() or ast.literal_eval() on each line, however the timestamp (2021/09/29T14:05:16) is an issue since it is not enclosed in quotes. Instead you can do some parsing to convert it into an object.

filename = 'offline_q.txt'
dict1 = {}
tag = "serial"
import ast
from dateutil import parser
def detect_type(x):
    try:
        return ast.literal_eval(x)
        # Caused by the date
    except SyntaxError: 
        return parser.parse(x)
        

with open(filename) as f:
    for line in f:
    raw = line.strip()
    processed = [i.replace('"',"") for i in raw.split(", ")]
    final_dict = {}
    for i in processed:
        x = i.split(": ")
        final_dict[x[0]] = detect_type(x[1])
  • Related