cgulliver
cgulliver

Reputation: 59

Extracting the number of value occurrences from a nested dictionary

I am trying to extract a sum of values from a nested dictionary and preserve the key name as a new dictionary.

I have been attempting various methods from researching here but below is the closest I have gotten.

Source dictionary:

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

Code:

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

Result:



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


What I need is the key and value with the totals:

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

Probably simple but not having success here. Thanks!

Upvotes: 1

Views: 370

Answers (2)

blhsing
blhsing

Reputation: 107040

You can use 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 becomes:

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

Upvotes: 2

Ajax1234
Ajax1234

Reputation: 71471

You can use 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()}

Output:

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

Upvotes: 1

Related Questions