繁体   English   中英

如何将字符串转换为包含两个具有各自值的键的字典对象列表?

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

我有一个外部文件,我必须将外部文件中的字符串转换为字典对象列表,其中包含键和相应的值。 问题是我已经尝试过的代码不断出现错误,例如“解包的值太多”。 我真的被困在这里了。

这是代码:

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"

您需要用,逗号分隔。 你还需要一dictionary

利用:

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'}

您在这里提供的信息确实太少了; 至少,文件内容的样本会有所帮助。 我可能猜到的是,每行的空格可能比您想象的要多,因此 split 返回两个以上的元素。

尝试添加拆分限制: (key, val) = line.split(' ', 2)

或更好地分析输入文件结构。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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