I'm using python to try and parse a JSON
file. Similar to this question, I want to count the number of occurrences for each combination of 2 values in the file:
Example JSON:
{
"first": "John",
"last": "Smith"
},
{
"first": "Adam",
"last": "Smith"
},
{
"first": "Adam",
"last": "Doe"
},
{
"first": "John",
"last": "Smith"
}
Desired Output would calculate something like this (less concerned about format more about count values and associated elements):
{
"first": "John", "last": "Smith", "count": 2
},
{
"first": "Adam", "last": "Smith", "count": 1
},
{
"first": "Adam", "last": "Doe", "count": 1
}
I've tried the below but it obviously only counts the unique "first" values and I'm not able to find a way to consider the second attribute "last" as well.
import json
from json import load
from collections import Counter
f = open('/PathToFile')
data = load(f)
c = Counter(i ['first'] for i in data)
print(c)
CodePudding user response:
You can count the tuples (first,last) in your counter:
Counter((i['first'], i['last']) for i in data)