Home > database >  Read text file to create list and then convert to dictionary python
Read text file to create list and then convert to dictionary python

Time:10-29

I am reading text file using

source= open(curr_file,"r")
lines= source.readlines()

This converts every line in my text file to a list, but some items in my list are created with double quotes while some are created with single quotes like below.

['[INFO] Name: Xxxx, section: yyyy, time: 21.2, status: 0\n', "proof:proof1,table: db.table_name,columns:['column_1'],count:10,status:SUCCESS\n",'run time: 30 seconds\n']

The first item in list is created with single quotes, while the second is created with double quotes.

When trying to convert the above to dictionary

new_line= dict(x.split(":"),1) for x in line.split(","))

It gives me a value error

Value error: dictionary update sequence element has length 1; 2 is required

The above error is because it considers the entire string under double quotes as single value and it's not able to convert it to dictionary.

Is there a way to convert it to single quotes instead of double. I tried using replace, strip. But nothing helps.

Expected output: { Name:Xxxx, section:yyyy, time:21.2, proof:proof1 table:db.table_name status: success }

CodePudding user response:

The quotes has nothing to do with the error. The exterior quotes of each line are not part of the str object. They are only printed to you know it is a str. The single quotes are switched to double because the content has single quotes in it, then single quotes cannot be used to delimit the str. But again, that is only a change in what is printed not in what is stored in memory.

Try to do it in steps and print the intermediate objects you get to debug the program.

for x in line: #prints nicer than print(line)
    print(x)

arg = [x.split(":",1) for x in line.split(",")]

for x in arg:    
    print(x)

new_line = dict(arg)

you should get printed tuples with two elements

CodePudding user response:

for convert your one line(str) to dict, you can use dictionary comprehension:

new_line = dict(x.split(":",1) for x in line.split()
  • Related