I've a JSON data file data.txt bellow :
{"Name": "Brian","scores": 8, "color": "red"}
{"Name": "Lina","scores": 2, "color": "blue"}
{"Name": "Brian","scores": 10, "color": "black"}
{"Name": "Brian","scores": 9, "color": "black"}
The json data as above JSON multiline in a file, I've code parse json decoded Object.
import json
studentsList = []
with open('data.txt') as f:
for jsonObj in f:
studentDict = json.loads(jsonObj)
studentsList.append(studentDict)
for student in studentsList:
if (student["Scores"]) >= 8:
print(student["Name"],student["Color"])
Results:
Brian red
Brian black
Brian black
Question: Now I need to filter out information the result when variable "scores" >= 8 and other variables in the object counting up 1 ?
Desire a result:
"Brian": 3 ,"black": 2 , "red": 1
Any ideas that can help me use on python3 .
CodePudding user response:
Your desired result is a dictionary, so let's create one
countObjects: Dict = {}
And then if search for the corresponding key, if it exists increment and if not create
for student in studentsList:
if (student["Scores"]) >= 8:
if student['Name'] in countObjects:
countObjects[student['Name']] = 1
else:
countObjects[student['Name']] = 1
print(student["Name"],student["Color"])
CodePudding user response:
I'm not sure if the keys you've mentioned here will stay consistent for all cases but just to generalize the solution, we can include a list keys
to keep track of all the values we want to include in the final output.
This approach basically uses another hashmap results
and counts the distinct values of all the variables mentioned in keys
.
This is a generalized solution, so if you want to include/exclude any of the values you can just update the list.
keys = ['Name', 'color']
results = {}
for student in studentsList:
if (student["scores"]) >= 8:
for i in keys:
if results.get(student[i]) is not None:
results[student[i]] =1
else:
results[student[i]] = 1
print(results)
Output
{'Brian': 3, 'red': 1, 'black': 2}
CodePudding user response:
You can use collections.Counter
to count the occurrences of each distinct value:
from collections import Counter
dict(Counter(i for d in studentsList if d.pop('scores') >= 8 for i in d.values()))
This returns:
{'Brian': 3, 'red': 1, 'black': 2}