从字典python中删除'Counter' [英] Removing 'Counter' from Dictionary python

查看:112
本文介绍了从字典python中删除'Counter'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the Counter class in Python to count the number of words in a key of a large python dictionary. I am creating a new dictionary with the keys being incremented numbers and the values being the return of the counter function. This is what my new dictionary looks like:

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

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

What I want to do, if possible, is remove the Counter and the parentheses ( and ) so that my dictionary looks like:

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

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

If that's not possible, can someone please tell me how to access the nested dictionaries inside the ()? Thank you

推荐答案

我看不到这样做的任何意义,Counterdict的子类,并且支持其所有方法,因此您应该没有问题保持原样,尽管仅出于这个问题,我将其转换回普通的dict:

I don't see any point of doing this, Counter is a subclass of dict and supports all of it's methods so you should have no problems leaving it as is, although just for the sake of this question I will convert it back to a normal 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建议)

For Python 2.7+ (as suggested by @Blender)

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

遍历各个子类,例如:

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

这篇关于从字典python中删除'Counter'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆