用其计数将一个字典的值转换为另一个字典

时间:2019-02-12 18:37:36

标签: python dictionary

我有如下字典:

d= {'a':['the','the','an','an'],'b':['hello','hello','or']}

我想将此字典转换为嵌套字典,其键值及其计数如下:

d = {'a':{'the':2,'an':2},'b':{'hello':2,'or':1}}

我可以按以下方式对字典中的值进行计数,但是无法将其值与其他字典一起转换为另一本字典。

length_dict = {key: len(value) for key, value in d.items()}

3 个答案:

答案 0 :(得分:2)

您可以改用collections.Counter

from collections import Counter
{k: dict(Counter(v)) for k, v in d.items()}

这将返回:

{'a': {'the': 2, 'an': 2}, 'b': {'hello': 2, 'or': 1}}

答案 1 :(得分:1)

使用Counter的字典理解

from collections import Counter
{k:{p:q for p,q in Counter(v).items()} for k,v in d.items()}

不使用计数器

def count_values(v):
    d={}
    for i in v:
        d[i]=d.get(i,0)+1
    return d

{k:{p:q for p,q in count_values(v).items()} for k,v in d.items()}

在此处使用熊猫为您提供更多选择(不是必需的)

from pandas import Series
df = pd.DataFrame(dict([ (k,Series(v)) for k,v in d.items() ]))
{c:df[c].value_counts().to_dict() for c in df.columns}

答案 2 :(得分:1)

d = {'a':['the','the','an','an'],'b':['hello','hello','or']}

我认为这样做很困难:

A::a