Tuhin
Tuhin

Reputation: 157

Extracting data from dictionary in python

I have a program from Dr.Chuck to print the sum of the counts from this data. The problem is. The count of the JSON is showing "2" when there are many..

import json
import urllib

url="http://python-data.dr-chuck.net/comments_42.json"
uh = urllib.urlopen(url)
data = uh.read()
print 'Retrieved',len(data),'characters'
print data

info = json.loads(data)
print 'User count:', len(info)

This line print 'User count:', len (info) is showing an output of 2. When there is a lot of data, hence I can only access 2 datas and not the rest.

I have no idea why. I can solve the counting sum part. Just not getting why am I only getting access to the first 2 data and the rest of the JSON is getting ignored.

Upvotes: 0

Views: 516

Answers (4)

Millie Smith
Millie Smith

Reputation: 4604

The json has two top level properties: note and comments. That is why you get a length of 2.

This will probably give you what you want:

len(info["comments"])

Upvotes: 1

histrio
histrio

Reputation: 1215

So, your json parsed to dict like

{"note":"bla", "comments":[...]}

Length of this should be 2 because it's only two keys in this dict. Right way to do you case is get comments itself and count them.

For example:

len(data.get('comments',[]))

Upvotes: 1

stoffen
stoffen

Reputation: 569

To count the number of comments:

print 'User count:', len(info["comments"])

To print the total "count":

count = 0
for comment in info["comments"]:
    count += comment["count"]
print 'Total count:', count

Upvotes: 1

Stefano
Stefano

Reputation: 3215

The Json is composed from note and comments. Inside comments there's another array of object. if you wanna access to that array you have to use this info['comments'] and then, if you want the length of that array, as you do, you can use len(info['comments'])

Upvotes: 0

Related Questions