我正在尝试从嵌套字典中提取值的总和并将键名保留为新字典。
我一直在尝试从这里进行研究的各种方法,但是下面是我得到的最接近的方法。
源词典:
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},
....
{
可能很简单,但是在这里没有成功。谢谢!
答案 0 :(得分:2)
您可以使用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
result
变为:
{'GET': {'GREEN': 2}, 'POST': {'GREEN': 2}, 'Query': {'GREEN': 1, 'RED': 1}, 'Cookie': {'RED': 2}, 'String': {'RED': 2}, 'Body': {'BLUE': 2}}
答案 1 :(得分:1)
您可以使用SELECT p.CnBio_ID, p.Type, max(p.Subj_Date_Last_Seen_1) as maxdate
from Phones p
GROUP BY p.CnBio_ID, p.Personal_Business, p.Type
:
collections.defaultdict
输出:
from collections import Counter, defaultdict
d = {'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'}}
new_d = defaultdict(list)
result = [i for b in d.values() for i in b.items()]
for a, b in result:
new_d[a].append(b)
new_result = {a:dict(Counter(b)) for a, b in new_d.items()}