简体   繁体   中英

How to convert the string to a list of dictionary objects containing two keys with respective values?

I have an external file, and I have to convert the strings from the external file to a list of dictionary objects, containing keys and with respective values. The problem is I keep getting error on the code I already tried, such as "too many values to unpack". I am really stuck in here.

Here is the code:

def open_file_and_get_content(filename):
    content = open('input.txt', 'r')
    return content


def convert_string_to_list(content):
    list= []
    for line in content:
        (key, val) = line.split()
        list[key] = val

The content of the input.txt looks like this:

"item1", "N"
"item2", "N"
"item3", "N"

You need to split by , comma. Also you need a dictionary

Use:

result = {}
with open(filename) as infile:
    for line in infile:
        key, value = line.replace('"', "").split(",")
        result[key] = value.strip()
print(result)  

Output:

{"Blake's Wings & Steaks": 'N',
 'Ebi 10': 'N',
 'Hummus Elijah': 'N',
 'Jumong': 'Y',
 'Kanto Freestyle Breakfast': 'Y',
 'Manam': 'N',
 'Refinery Coffee & Tea': 'N',
 'Shinsen Sushi Bar': 'N',
 'The Giving Cafe': 'N',
 'Tittos Latin BBW': 'N',
 'el Chupacabra': 'Y'}

You are truly giving too little information here; a sample of the file content, at least, would help. All I may guess is, there are possibly more spaces per line than you think, thus split return more than two elements.

Try to add a split limit: (key, val) = line.split(' ', 2)

or to better analyze the input file structure.

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