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:
JavaScript
x
11
11
1
def open_file_and_get_content(filename):
2
content = open('input.txt', 'r')
3
return content
4
5
6
def convert_string_to_list(content):
7
list= []
8
for line in content:
9
(key, val) = line.split()
10
list[key] = val
11
The content of the input.txt looks like this:
JavaScript
1
4
1
"item1", "N"
2
"item2", "N"
3
"item3", "N"
4
Advertisement
Answer
You need to split by ,
comma. Also you need a dictionary
Use:
JavaScript
1
7
1
result = {}
2
with open(filename) as infile:
3
for line in infile:
4
key, value = line.replace('"', "").split(",")
5
result[key] = value.strip()
6
print(result)
7
Output:
JavaScript
1
12
12
1
{"Blake's Wings & Steaks": 'N',
2
'Ebi 10': 'N',
3
'Hummus Elijah': 'N',
4
'Jumong': 'Y',
5
'Kanto Freestyle Breakfast': 'Y',
6
'Manam': 'N',
7
'Refinery Coffee & Tea': 'N',
8
'Shinsen Sushi Bar': 'N',
9
'The Giving Cafe': 'N',
10
'Tittos Latin BBW': 'N',
11
'el Chupacabra': 'Y'}
12