简体   繁体   English

从文本文件(Python 3)导入数据时,向预先存在的字典键添加值

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

I'm trying to create a dictionary by pulling from a text file that looks something like this,我正在尝试通过从看起来像这样的文本文件中提取来创建字典,

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

Right now I'm using现在我正在使用

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


f.close()

The problem I'm running into is that when "Fred" appears multiple times it just overwrites the previous value (Amy) and replaces it with the newest one (Tom), is there any way I can just add a new value if the key already exists, even when pulling from a txt file?我遇到的问题是,当“Fred”多次出现时,它只会覆盖以前的值(Amy)并用最新的值(Tom)替换它,如果键已经存在,即使从 txt 文件中提取?

Thanks!谢谢!

You could replace the value of the dictionary with a list:您可以用列表替换字典的值:

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()

This is a good use case for defaultdict , which upon accessing a key creates a default value.这是defaultdict一个很好的用例,它在访问一个键时会创建一个默认值。

If we use a list as a default in this case, your code can be simplified to the following:如果我们在这种情况下使用列表作为默认值,您的代码可以简化为以下内容:

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())

That way you will have the result values for each key as you desire.这样您就可以根据需要获得每个键的结果值。

Note the with line, which ensures that file handle is closed at the end of the block.请注意with行,它确保文件句柄在块的末尾关闭。 You don't have to do this, but it saves you having to do an f.close() later (or just rely on the process closing and dropping the handle).您不必这样做,但它可以节省您稍后执行f.close()f.close() (或仅依靠进程关闭和放下句柄)。

You can use set instead of list if you want to elements don't repeat selves:如果你想让元素不重复,你可以使用 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()

or with defaultdict:或使用 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