我正在使用 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}...}
如果那不可能,有人可以告诉我如何访问 () 中的嵌套字典吗?谢谢
最佳答案
我看不出这样做有什么意义,Counter
是 dict
的子类并且支持它的所有方法,所以你应该没有问题,保持原样,尽管只是为了这个问题,我会将其转换回普通的 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/