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

Python 将一个字典的值及其计数转换为另一个字典,python,dictionary,Python,Dictionary,我有一本字典如下: d= {'a':['the','the','an','an'],'b':['hello','hello','or']} d = {'a':{'the':2,'an':2},'b':{'hello':2,'or':1}} 我想将此字典转换为一个嵌套字典,其中包含键的值及其计数,如下所示: d= {'a':['the','the','an','an'],'b':['hello','hello','or']} d = {'a':{'the':2,'an':2},'b':{'h

我有一本字典如下:

d= {'a':['the','the','an','an'],'b':['hello','hello','or']}
d = {'a':{'the':2,'an':2},'b':{'hello':2,'or':1}}
我想将此字典转换为一个嵌套字典,其中包含键的值及其计数,如下所示:

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()}

您可以使用集合。计数器:

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

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

使用计数器的词典理解

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 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()}
在此处使用Pandas(非必需)提供更多选项,但仍然

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}

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

我认为应该这样做:

from collections import Counter
new_dict = {}
for k in d.keys():
  aux_counter = Counter(d[k])
  new_dict [k] = {}
  for c, v in zip(aux_counter.keys(), aux_counter.values()):
    new_dict[k][c] = v