python键值对数组_字典与Python中不同类型的数组作为值

I am learning Python and I have a dictionary like this:

category = { "World news": [0], "Politics": [0], ... }

where now I am reading articles from a file. Every article has a category. So I would like the 0 I have to every key to be incremented by 1 when a category is meet and to augment the array every key has with the article it found. So the output would be:

category = { "World news": [2, "foo bla content of", "content of 2nd article"],

"Politics": [1, "only 1 article here"],

...

}

Here is what I have now:

for row in iter_reader:

category[row[4]][0] = category[row[4]][0] + 1

category[row[4]].append(category[row[3]])

but I think it interprets an article as a key and throws a relevant error:

File "./wordCloud.py", line 41, in

category[row[4]].append(category[row[3]])

KeyError: 'When Apple unveiled its in January 2010..

Any ideas please?

row[4] is the category of the article.

row[3] is the content of the article.

As Bryan Oakley said, I do not need to keep a counter, so I am now thinking in this direction...

解决方案

In the third line, you are appending category[row[3]] where you should probably be appending simply row[3]. You are currently using row[3] as an index for the category list, but I suspect row[3] is actually the content you want to append.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值