简体   繁体   中英

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.

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"])

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

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',[]))

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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM