我要创建一个基于CSV文件看起来像这样一本字典创建字典:从文本文件的Python
'song, 2000, 184950'
'boom, 2009, 83729'
'boom, 2010, 284500'
'boom, 2011, 203889'
'pow, 2000, 385920'
'pow, 2001, 248930'
从这个
,我要创建一个包含字的字典键,然后将类对象列表作为值。
这是我迄今为止...
class Counter():
__slots__ = ('year', 'count')
_types = (int, int)
def readfile(file):
d = dict()
with open(file) as f:
for line in f:
element = line.split(,)
for word in element:
if word in d:
d[word].append([Count(int(element[1]), int(element[2]))])
else:
d[word] = [Count(int(element[1]), int(element[2]))]
print(d)
我得到的输出是奇怪的,它是给我一本词典类似地雷应该是什么样子,但它的使用计数(183930 )作为关键字而不是名称。如果它已经在字典中列出,我还需要它将该类添加到该值。
例如,因为'繁荣'应该已经在字典中{'boom' : Count(year = 2009, count = 83729)}
我希望那里有一个计数对象列表中的一个值。
预期输出:
{'song' : [Count(year= 2000, count= 184950)], 'boom' : [Count(year=2009, count=83729),
Count(year=2010, count= 284500), Count(year=2011, count=203889)], 'pow' : ...etc..}
@Martijn你确定'''应该在csv例子中?我认为他们对字符串有意义,但不能作为示例csv。 – Vyktor 2014-11-24 20:10:57
@Vyktor:OP在他们的样本中使用了这个;我会留给他们删除它。 – 2014-11-24 20:12:59
您的代码无效;它缺少引号(以逗号为例),而发布的'Counter()'类将不起作用。你可以给我们*工作代码*? – 2014-11-24 20:14:50