我想将 Counter 转换为 Json 对象,以便将此 Counter 保存到数据库中。问题是当我解码 Json 对象时,我无法再更新我的计数器:
from collections import Counter
import json
counter = Counter(['a','a','b','a'])
counterJson = json.dumps(counter)
counter = json.loads(counterJson)
counter.update(['a','e'])
我收到此错误消息:
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
counter.update(['a','e'])
ValueError: dictionary update sequence element #0 has length 1; 2 is required
最佳答案
counter
不再是 Counter
,它是 json.loads
之后的 dict
。因此,您需要将其转换为计数器
。然后,您可以使用另一个 Counter
更新一个 Counter
,如下所示
counter = Counter(json.loads(counterJson))
counter.update(Counter(["a", "e"]))
print counter
输出
Counter({u'a': 4, u'b': 1, 'e': 1})
关于python - 将 Counter 编码为 Json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20091876/