如何将字符串转换为包含具有各自值的两个键的字典对象列表?
How to convert the string to a list of dictionary objects containing two keys with respective values?
我有一个外部文件,我必须将外部文件中的字符串转换为包含键和相应值的字典对象列表。问题是我已经尝试过的代码不断出现错误,例如 "too many values to unpack"。我真的卡在这里了。
代码如下:
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
input.txt 的内容如下所示:
"item1", "N"
"item2", "N"
"item3", "N"
您在这里提供的信息确实太少了;至少文件内容的样本会有所帮助。
我可能猜测的是,每行的空格可能比你想象的要多,因此拆分 return 超过两个元素。
尝试添加拆分限制:
(key, val) = line.split(' ', 2)
或更好地分析输入文件结构。
您需要用 ,
逗号分隔。你还需要一个 dictionary
使用:
result = {}
with open(filename) as infile:
for line in infile:
key, value = line.replace('"', "").split(",")
result[key] = value.strip()
print(result)
输出:
{"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'}
我有一个外部文件,我必须将外部文件中的字符串转换为包含键和相应值的字典对象列表。问题是我已经尝试过的代码不断出现错误,例如 "too many values to unpack"。我真的卡在这里了。
代码如下:
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
input.txt 的内容如下所示:
"item1", "N"
"item2", "N"
"item3", "N"
您在这里提供的信息确实太少了;至少文件内容的样本会有所帮助。 我可能猜测的是,每行的空格可能比你想象的要多,因此拆分 return 超过两个元素。
尝试添加拆分限制: (key, val) = line.split(' ', 2)
或更好地分析输入文件结构。
您需要用 ,
逗号分隔。你还需要一个 dictionary
使用:
result = {}
with open(filename) as infile:
for line in infile:
key, value = line.replace('"', "").split(",")
result[key] = value.strip()
print(result)
输出:
{"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'}