gpt4 book ai didi

python - 从嵌套字典中提取值出现的次数

转载 作者:行者123 更新时间:2023-11-30 21:59:02 24 4
gpt4 key购买 nike

我正在尝试从嵌套字典中提取值的总和并将键名称保留为新字典。

我一直在尝试各种方法来研究这里,但以下是我得到的最接近的方法。

来源词典:

result_data=

{
"uhawjjh4": {
"GET": "GREEN",
"POST": "GREEN",
"Query": "GREEN",
"Cookie": "RED",
"String": "RED",
"Body": "BLUE"
},
"bcfp19sg": {
"GET": "GREEN",
"POST": "GREEN",
"Query": "RED",
"Cookie": "RED",
"String": "RED",
"Body": "BLUE"
}
}

代码:

    result_data_global = Counter()
for data in result_data.values():
result_data_global += Counter(data.keys())

结果:



{
"GREEN": 5,
"RED": 5,
"BLUE": 2,
}


我需要的是总计的键和值:

{
"GET": {"GREEN": 2},
"POST": {"GREEN": 2},
"Query": {"GREEN": 1, “RED”: 1},
....
{

可能很简单,但这里没有成功。谢谢!

最佳答案

您可以使用dict.setdefault:

result = {}
for d in result_data.values():
for k, v in d.items():
result[k][v] = result.setdefault(k, {}).get(v, 0) + 1

结果变为:

{'GET': {'GREEN': 2}, 'POST': {'GREEN': 2}, 'Query': {'GREEN': 1, 'RED': 1}, 'Cookie': {'RED': 2}, 'String': {'RED': 2}, 'Body': {'BLUE': 2}}

关于python - 从嵌套字典中提取值出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54702230/

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