Skip to content Skip to sidebar Skip to footer

Retrieving Items From A Dictionary Data Type Created From A Json Request

I've tried every way I can find to loop through the member items in the JSON returned below by this code: import requests,string,simplejson as json from pprint import pprint data=

Solution 1:

The data in your code is a python dictionary. A key value pair.

You can access items in a dictionary with a variable[key] format. In your case as:

data['members']

this prints

[[{u'member_amt_pledged': u'10.00',
   u'member_amt_recvd': None,
   u'member_id': u'1',
   u'name': u'Murray Hight'},
  {u'member_amt_pledged': u'10.00',
   u'member_amt_recvd': None,
   u'member_id': u'4',
   u'name': u'Martin Tunis'}]]

so data['members'] is a list of a list. Access it's first item as data['members'][0]. This is still a list. So you iterate over it as:

for item in data['members'][0]:
    print(item)

this gives you:

{u'member_amt_recvd': None, u'member_amt_pledged': u'10.00', u'name': u'Murray Hight', u'member_id': u'1'}
{u'member_amt_recvd': None, u'member_amt_pledged': u'10.00', u'name': u'Martin Tunis', u'member_id': u'4'}

As you can see, each of these are dictionaries, so you access it's items as:

for item in data['members'][0]:
    print(item['member_amt_pledged'])
    print(item['member_amt_recvd'])
    print(item['member_id'])
    print(item['name'])

this gives you:

10.00None1
Murray Hight
10.00None4
Martin Tunis

Hope this helps.

Solution 2:

To loop the items of the JSON dictionary, you would do the following:

for key, valindata.items():
    print key, val

For a larger dataset, you should use iterators:

for key, valindata.iteritems(): 
    print key, val

More on dictionaries

Post a Comment for "Retrieving Items From A Dictionary Data Type Created From A Json Request"