简体   繁体   English

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

[英]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: input.txt 的内容如下所示:

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

You need to split by , comma.您需要用,逗号分隔。 Also you need a dictionary你还需要一dictionary

Use:利用:

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

Output: 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.我可能猜到的是,每行的空格可能比您想象的要多,因此 split 返回两个以上的元素。

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

or to better analyze the input file structure.或更好地分析输入文件结构。

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

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