如何将Counter对象转换为dict? [英] How to convert Counter object to dict?
问题描述
数据框:
pair = collections.defaultdict(collections.Counter)
例如
pair = {'doc1': {'word1':4, 'word2':3},
'doc2': {'word1':2, 'word3':4},
'doc3': {'word2':2, 'word4':1},
...}
我想保留数据框,但更改此部分的类型{'word1':4, 'word2':3}
{'word1':2, 'word3':4}``...
现在是Counter
,我需要一个dict
.
I want to keep the data frame but alter the type of this part {'word1':4, 'word2':3}
{'word1':2, 'word3':4}``...
It is now a Counter
and I need a dict
.
我尝试这样做是为了从pair
获取数据,但是我不知道如何为每个文档创建dict
:
I tried this to get the data from pair
, but I do not know how to create a dict
for each doc:
new_pair = collections.defaultdict(collections.Counter)
for doc, tab in testing.form.items():
for word, freq in tab.items():
new_pair[doc][word] = freq
我不想更改输出.我只需要每个文档中的,数据类型为dict
,而不是Counter
.
I do not want to change the output. I just need that in each doc, the data type is dict
, not Counter
.
推荐答案
Counter
已经是dict
-或其子类.但是,如果由于某种原因确实确实需要dict
,那么它是单线的:
A Counter
is already a dict
- or, a subclass of it. But, if you really need exactly a dict
for some reason, then its a one-liner:
>>> c = Counter(word1=4, word2=3)
>>> c
Counter({'word1': 4, 'word2': 3})
>>> dict(c)
{'word1': 4, 'word2': 3}
任何映射(行为类似于字典的任何内容)都可以传递到dict
中,您将获得具有相同内容的dict
.无需迭代就可以自己构造它.
Any Mapping (anything that behaves like a dictionary) can be passed into dict
, and you will get a dict
with the same contents. There is no need to iterate over it to construct it yourself.
这将为您提供一个循环,主体中只有一行,而不是嵌套循环.但是任何形式的代码:
This gives you one loop, with one line in the body instead of a nested loop. But any code of the form:
thing = a new empty collection
for elem in old_thing:
Add something to do with elem to thing
通常可以使用生成器表达式或列表,集合或字典理解在一行中完成.我们正在构建一个dict
,因此,一个 dict理解(示例似乎是您最感兴趣的部分).我将把它作为读者的练习. ;-)
Can usually be done in one line using a generator expression or a list, set or dict comprehension. We're building a dict
, so a dict comprehension (the Examples section is what you're most interested in) seems likely. I'll leave coming up with it as an exercise for the reader. ;-)
这篇关于如何将Counter对象转换为dict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!