簡體   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