簡體   English   中英

從 txt 文件在 python 中創建字典

[英]Creating a dictionary in python from txt file

我知道以前有人問過這個問題的變體,但我仍在努力將 txt 文件移動到字典中。 txt 文件的名稱和數量用“:”分隔。 我遇到了條帶 function 沒有刪除空白行的問題。 我遇到的另一個問題是,如果兩行具有相同的鍵,我想對這些值求和。 我對 python 還是比較陌生,所以任何幫助將不勝感激!

在此處輸入圖像描述

非常簡單但不安全,有很多地方會導致程序崩潰,但您可能並不關心

def loadToDict(path):
    f = open(path)
    d = {} 
    for line in f:
        line = line.strip()
        if line == "": # ignore empty line
            continue
        key, value = line.split(":") # decompose
        if key in d: # contains so add
            d[key] += int(value)
        else:
            d[key] = int(value)
    return d

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM