【发布时间】:2017-01-04 17:35:55
【问题描述】:
如何将此代码的输出放入包含键值对总数的字典中?
import re
from collections import Counter
splitfirst = open('output.txt', 'r')
input = splitfirst.read()
output = re.split('\n', input)
for line in output:
counter = Counter(line)
ab = counter.items() #gives list of tuples will be converted to dict
abdict = dict(ab)
print abdict
这是我得到的示例:
{' ': 393, '-': 5, ',': 1, '.': 1}
{' ': 382, '-': 4, ',': 5, '/': 1, '.': 5, '|': 1, '_': 1, '~': 1}
{' ': 394, '-': 1, ',': 2, '.': 3}
{'!': 1, ' ': 386, 'c': 1, '-': 1, ',': 3, '.': 3, 'v': 1, '=': 1, '\\': 1, '_': 1, '~': 1}
{'!': 3, ' ': 379, 'c': 1, 'e': 1, 'g': 1, ')': 1, 'j': 1, '-': 3, ',': 2, '.': 1, 't': 1, 'z': 2, ']': 1, '\\': 1, '_': 2}
我有 400 个这样的字典,理想情况下我必须将它们合并在一起,但如果我理解正确,Counter 不会全部提供,而是一个接一个地提供。
任何帮助将不胜感激。
【问题讨论】:
标签: python python-2.7 dictionary merge counter