python - 从字典 python 中删除 'Counter'

标签 python dictionary counter

我正在使用 Python 中的 Counter 类来计算大型 Python 字典的键中的单词数。我正在创建一个新字典,其中的键是递增的数字,值是计数器函数的返回值。这是我的新词典的样子:

TP = {1:Counter({u'x':1, u'b':1, u'H':3}),2:Counter({u'j':1, u'm':4, u'e':2})...}

如果可能的话,我想做的是删除 Counter 和括号 ( and ),这样我的字典看起来像:

TP = {1:{u'x':1, u'b':1, u'H':3}, 2:{u'j':1, u'm':4, u'e':2}...}

如果那不可能,有人可以告诉我如何访问 () 中的嵌套字典吗?谢谢

最佳答案

我看不出这样做有什么意义,Counterdict 的子类并且支持它的所有方法,所以你应该没有问题,保持原样,尽管只是为了这个问题,我会将其转换回普通的 dict:

>>> from collections import Counter
>>> tp = {1:Counter({u'x':1, u'b':1, u'H':3}),2:Counter({u'j':1, u'm':4, u'e':2})}
>>> dict((k, dict(v)) for k, v in tp.iteritems())
{1: {u'x': 1, u'b': 1, u'H': 3}, 2: {u'e': 2, u'j': 1, u'm': 4}}

对于 Python 2.7+(由@Blender 建议)

{k: dict(v) for k, v in tp.iteritems()}

遍历子字典,例如:

for w, c in tp[1].iteritems():
    print w, c

关于python - 从字典 python 中删除 'Counter',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11731633/

相关文章:

javascript - 瞬时字数计数器

python - Jupyter 实验室 - dask-labextension 不起作用

python - 如何使用Python ast模块的NodeTransformer类

ios - 如何从Swift 4/json字典中的多值键检索单个值?

java - Proto3编译器没有为Map字段生成put方法

python - 通过 Python 字典元素隐式迭代

java - 文本文件的字符数

python - 异步和异步错误——TypeError : 'coroutine' object is not callable

python - Xarray - 将数据变量更改为维度