簡體   English   中英

從文本文件(Python 3)導入數據時,向預先存在的字典鍵添加值

[英]Adding a value to a pre existing dictionary key when importing the data from a text file (Python 3)

我正在嘗試通過從看起來像這樣的文本文件中提取來創建字典,

Fred beats Amy  
Fred beats Tom  
Tom beats Amy   
Amy beats Jordan 

現在我正在使用

f = open("RockPaperScissors.txt", 'r')  
fwDict = {}  
for line in f:  
    k, v = line.strip().split('beats')  
    fwDict[k.strip()] = v.strip()  


f.close()

我遇到的問題是,當“Fred”多次出現時,它只會覆蓋以前的值(Amy)並用最新的值(Tom)替換它,如果鍵已經存在,即使從 txt 文件中提取?

謝謝!

您可以用列表替換字典的值:

f = open("RockPaperScissors.txt", 'r')  
fwDict = {}  
for line in f:  
    k, v = line.strip().split('beats')

    # If we already have the key in the dictionary, just append to the list
    if k.strip() in fwDict:
        fwDict[k.strip()].append(v.strip())

    # If we don't have the key in the dict, create the new key-value pair as a list
    else:
        fwDict[k.strip()] = [v.strip()]


f.close()

這是defaultdict一個很好的用例,它在訪問一個鍵時會創建一個默認值。

如果我們在這種情況下使用列表作為默認值,您的代碼可以簡化為以下內容:

from collections import defaultdict

fw_dict = defaultdict(list)

with open('RockPaperScissors.txt', 'r') as f:
    for line in f:
        k, v = line.strip().split('beats')
        fw_dict[k.strip()].append(v.strip())

這樣您就可以根據需要獲得每個鍵的結果值。

請注意with行,它確保文件句柄在塊的末尾關閉。 您不必這樣做,但它可以節省您稍后執行f.close()f.close() (或僅依靠進程關閉和放下句柄)。

如果你想讓元素不重復,你可以使用 set 而不是 list:

f = open("RockPaperScissors.txt", 'r')  
fwDict = {}  
for line in f:  
    k, v = line.strip().split('beats')
    if k.strip() in fwDict:
        fwDict[k.strip()].add(v.strip())
    else:
        a = set()
        a.add(v.strip())
        fwDict[k.strip()] = a


f.close()

或使用 defaultdict:

from collections import defaultdict

f = open("RockPaperScissors.txt", 'r')  
fwDict = defaultdict(set)
for line in f:  
    k, v = line.strip().split('beats')
    fwDict[k.strip()].add(v.strip())


f.close()

暫無
暫無

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

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