Reputation: 23
I have a file named 'names.txt'. Each line of the file is in this format (year,name,gender,count). For example (1980,david,M,12).
I want to read each line and then seperate it into dictionaries named (year,name,gender,count). Everytime I run my program, it sets (year,name,gender,count) to the last thing that it reads, instead of adding it into the dictionary. Do I have to add an append to somewhere in my code so that it does what I want it to?
f = open('names.txt')
lines = 0
years = {}
names = {}
gender = {}
count = {}
for line in f:
lines += 1
years, names, gender, count = line.strip().split(",")
print(names)
return lines
Upvotes: 0
Views: 71
Reputation: 103
how about this. using defaultdict
from collections import defaultdict
f = open('names.txt')
lines = 0
d = defaultdict(list)
for line in f:
year, name, gender, count = line.strip().split(",")
d[year].append((name,gender,count))
it depends on the data though.
Upvotes: 1
Reputation: 16184
Dictionaries are build for search by keys. By your current usage, it looks like you're looking for overlapping lists, because no of the fields has a key:
lines = 0
years, names, genders, counts = [], [], [], []
for line in f:
year, name, gender, count = line.strip().split(",")
years.append(year)
names.append(name)
genders.append(gender)
counts.append(int(count))
lines += 1
However, creating dictionary makes sense in this case, when saving all the data under the key of the name:
lines = 0
people = {}
for line in f:
year, name, gender, count = line.strip().split(",")
people[name] = {'year': year, 'gender': gender, 'count': int(count)}
lines += 1
Upvotes: 2