gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:12:37 26 4
gpt4 key购买 nike

我有一个字典如下:

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

关于python - 将字典的值转换为另一个字典及其计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54656612/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com