Reputation: 23
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?
Thanks!
Upvotes: 2
Views: 87
Reputation: 11
You can use set instead of list if you want to elements don't repeat selves:
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:
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()
Upvotes: 0
Reputation: 2046
This is a good use case for defaultdict
, which upon accessing a key creates a default value.
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. 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).
Upvotes: 1
Reputation: 1164
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()
Upvotes: 1