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"
Advertisement
Answer
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'}