1

I want to get sum of count Below is my json:

json_data={
"note":abbcccc,
"comments":
    [{"count":100,"name"=leven},{"count":120,"name"=sam}]
}

How do I get the sum of all counts (100+120)

I can get indivdual like this:

data=json.loads(json_data)
count=data["comments"][0]["count"]

But stuck on "How to loop though it"

3 Answers 3

4

Use sum:

count = sum(c["count"] for c in data["comments"])
Sign up to request clarification or add additional context in comments.

Comments

2

Loop through each of the items in the comments list. Then pick "count" from each dict in that list. And add up.

data=json.loads(json_data)
total = 0
for each_counts in data["comments"]
    total += each_counts["count"]

This can be shortened to:

total = sum(each_count["count"] for each_count in data["comments"]

Comments

1

You can loop through it like any list:

count = 0
for c in data['comments']:
  count += c['count']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.