简体   繁体   中英

how to convert text file data to python dictionary

I have seen quite a few questions like this however none like mine specific separation of items with newlines.

text file:

John
City: New york
Job: surgeon
Happy: no

Terry
City: Miami
House: Yes
Job: nurse
Married: No

Joe
City: LA
Married: No
Job: None

Dictionary should have separate items which are determined by the blank line in the text document, and the format stays the same like= 'key': 'value' but there isnt a predetermined set amount per item of the dict. could be 4 items like joe or three like john.

So far i have:

with open(file.txt) as file:
    id = {}
    for line in file:
        if line is not '\n'
            k,v = line.strip().split(': ', 1)
            id[k] = v.strip()
            
print(id)

I know this is incorrect and the previous quides have been no help when dealing with newlines.

I expect it to look like:

{
    "John": {
        "City": "new york",
        "Job": "surgeon",
        "Happy": "no"
    }, 
    "Terry": {
        "City": "Miami",
        "House": "Yes",
        "Job": "nurse",
        "Married": "No"
    },   
    "Joe": {
        "City": "LA",
        "Married": "No",
        "Job": "None"
    }
}
        
            

Try:

text = """\
John
City: New york
Job: surgeon
Happy: no

Terry
City: Miami
House: Yes
Job: nurse
Married: No

Joe
City: LA
Married: No
Job: None"""

out = {}
for group in text.split("\n\n"):
    lines = group.split("\n")
    out[lines[0]] = dict(l.split(": ") for l in lines[1:])

print(out)

Prints:

{
    "John": {"City": "New york", "Job": "surgeon", "Happy": "no"},
    "Terry": {"City": "Miami", "House": "Yes", "Job": "nurse", "Married": "No"},
    "Joe": {"City": "LA", "Married": "No", "Job": "None"},
}

EDIT: To read the text from a file:

with open("your_file.txt", "r") as f_in:
    text = f_in.read().strip()

out = {}
for group in text.split("\n\n"):
    lines = group.split("\n")
    out[lines[0]] = dict(l.split(": ") for l in lines[1:])

print(out)

EDIT 2:

If your file contains:

City: New york
Job: surgeon
Happy: no

City: Miami
House: Yes
Job: nurse
Married: No

City: LA
Married: No
Job: None

then:

with open("your_file.txt", "r") as f_in:
    text = f_in.read().strip()

out = []
for group in text.split("\n\n"):
    lines = group.split("\n")
    out.append(dict(l.split(": ") for l in lines))

print(out)

prints:

[
    {"City": "New york", "Job": "surgeon", "Happy": "no"},
    {"City": "Miami", "House": "Yes", "Job": "nurse", "Married": "No"},
    {"City": "LA", "Married": "No", "Job": "None"},
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM