Rem
Rem

Reputation: 379

Looping through Dictionary of Unicode Data

I'm trying to loop through a list of unicode data. type(d['results']) is a list. However, organization_fields is actually a dict but formatted as unicode when looking at the load. The question is, how can I access organization_fields? I've tried to change the format using ast.literal_eval(k) but have had some errors in trying to do so.

Also, I'm getting my response r and saving it as d = r.json()

I have

       for a in d['results']:
 ...:     for k,v in a.iteritems():
 ...:         print k
 ...:         print type(k)  
 ...:         print('------break-----')

Here is the output:

 name
 <type 'unicode'>
 ------break-----
 shared_comments
 <type 'unicode'>
 ------break-----
 url
 <type 'unicode'>
 ------break-----
 organization_fields
<type 'unicode'>
------break-----

organization_fields

    u'organization_fields': {
       u'account_type': None, 
       u'id':  u'some_id', 
       u'value': None
  }, 

UPDATE

When i try printing d['results'][0] I do get a list of items that are in here Ex. url, name, except organization_fields does not exist in it. It only exists when i loop through a in the above for loop

Upvotes: 1

Views: 308

Answers (2)

Captain&#39;Flam
Captain&#39;Flam

Reputation: 537

I'm not sure to understand your question...

But if I did, you should try something like :

print d['result'][0]['organization_fields']['id']

which should print

some_id

--> I don't think there's any "unicode data" : there are dictionnaries with unicode strings as keys.

Upvotes: 0

Evan
Evan

Reputation: 2301

organization_fields is not stored as unicode. The key is a unicode string, but the type of the value stored by the key u'organization_fields' is a dictionary of more values stored with unicode string keys. Accessing values of organization fields is identical to accessing values of any other dictionary.

If you want to access organization_fields in your for loop:

for a in d['results']:
    org_fields = a['organization_fields']
    print org_fields

Edit: It does not sound like every element of d['results'] contains a dictionary with a value stored by the key organization_fields. This should do the trick.

for a in d['results']:
    if 'organization_fields' in a:
        org_fields = a['organization_fields']
        print org_fields

If you want to see which index of d['results'] contains the value of organization_fields, then do this:

for i, a in enumerate(d['results']):
    if 'organization_fields' in a:
        org_fields = a['organization_fields']
        print org_fields
        print 'index: %s' % i

Then, with the index you printed from there, you can access it directly:

org_fields = d['results'][index printed]['organization_fields']

Upvotes: 1

Related Questions