繁体   English   中英

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

[英]Convert values of a dictionary to another dictionary with their counts

我有以下字典:

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

您可以使用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}}

使用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}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM