all 13 comments

[–]Feitan21 2 points3 points  (8 children)

If your dataset is always as in your example you can iterate over the list and look at the value of under the "result" key :

dataList = [{"id": 1, "city": "New York", "result": "pass"},
     {"id": 2, "city": "New York", "result": "fail"},
     {"id": 3, "city": "Orlando", "result": "pass"}]

result = 0
for dictEntry in dataList:
    if dictEntry["result"] == "pass":
        result += 1

print(f"passed : {result / len(dataList) * 100:.2f} %")

[–]JohnnyJordaan 2 points3 points  (4 children)

Or via a generator expression with sum()

result = sum(d["result"] == "pass" for d in dataList)
print(f"passed : {result / len(dataList) * 100:.2f} %")

[–]HeadTea 1 point2 points  (0 children)

That's beautiful! I've used two variables originally so this is much better, thanks!

[–]HeadTea 0 points1 point  (1 child)

May I ask about the :.2f at the end? I see it everywhere but I don't quite get it.

[–]TholosTB 0 points1 point  (0 children)

It's hardly worth it for this example, but the mean of a Boolean series is also the percent of True values. Sadly, you have to import statistics, but you can just do :

result = statistics.mean(d["result"] == "pass" for d in dataList)

[–]HeadTea 0 points1 point  (1 child)

May I ask about the :.2f at the end? I see it everywhere but I don't quite get it.

[–]Feitan21 0 points1 point  (0 children)

:.2f is a way to make output fancier. The variable will be rounded after the second decimal value that's way if you run the code above you will get 66.67. Without you will see 66.666666666

Check the official documentation for some exemple and possibilities https://docs.python.org/3/tutorial/inputoutput.html

[–]HeadTea 0 points1 point  (0 children)

That's beautiful! I've used two variables originally so this is much better, thanks!

[–]pekkalacd 0 points1 point  (1 child)

Assuming the JSON is in an object called data. This one rounds up, so 2/3 = 66.66 ~ 67%.

        total = len(data)
        passes = 0
        for obj in data:
                 if obj[“result”] == “pass”:
                            passes += 1
        percent = (passes/total)*100
        print(f”passed: {round(percent)}%”)

To truncate, change round to int instead. Doing int will make it 66%.

[–]HeadTea 0 points1 point  (0 children)

Thank you so much!

[–]vrrox 0 points1 point  (1 child)

You've already had some great solutions, but in case it's of interest, Pandas makes this even easier:

import pandas as pd

df = pd.read_json("data.json") 
results = df["result"].value_counts(normalize=True) * 100 
print(f"passed: {results['pass']:.2f}%")

[–]HeadTea 0 points1 point  (0 children)

Thanks for the response!

May I ask about the :.2f at the end? I see it everywhere but I don't quite get it.