RomanK
RomanK

Reputation: 109

How do i get a value buried in a OrderedDict

I have a variable "case" that calls OrderedDict:

OrderedDict([('totalSize', 1),
         ('done', True),
         ('records',
          [OrderedDict([('attributes',
                         OrderedDict([('type', 'Case'),
                                      ('url',
                                       '/services/data/v38.0/sobjects/Case/5003700000ReKcJAAV')])),
                        ('Id', '5003700000ReKcJAAV')])])])

I want a variable 'Id' to return '5003700000ReKcJAAV'. Is there a way to do that?

I'm using Python 3.6.5

Upvotes: 0

Views: 55

Answers (3)

Soumendra
Soumendra

Reputation: 1624

This looks ugly but, works.

from collections import OrderedDict
z = OrderedDict([('totalSize', 1),
         ('done', True),
         ('records',
          [OrderedDict([('attributes',
                         OrderedDict([('type', 'Case'),
                                      ('url',
                                       '/services/data/v38.0/sobjects/Case/5003700000ReKcJAAV')])),
                        ('Id', '5003700000ReKcJAAV')])])])
print(z.get('records')[0].get('Id'))

Output:

5003700000ReKcJAAV

Upvotes: 1

RomanK
RomanK

Reputation: 109

It was easier, then i was expecting. I just needed to:

Id = case['records'][0]['Id']

Upvotes: 0

hygull
hygull

Reputation: 8740

You can also try the below code.

from collections import OrderedDict
import json

l = [('totalSize', 1),
         ('done', True),
         ('records',
          [OrderedDict([('attributes',
                         OrderedDict([('type', 'Case'),
                                      ('url',
                                       '/services/data/v38.0/sobjects/Case/5003700000ReKcJAAV')])),
                        ('Id', '5003700000ReKcJAAV')])])]
ordDict = OrderedDict(l)

print json.dumps(ordDict, indent=4)
"""
{
    "totalSize": 1,
    "done": true,
    "records": [
        {
            "attributes": {
                "type": "Case",
                "url": "/services/data/v38.0/sobjects/Case/5003700000ReKcJAAV"
            },
            "Id": "5003700000ReKcJAAV"
        }
    ]
}
"""

print ordDict['records'][0]['Id'] # 5003700000ReKcJAAV

Upvotes: 0

Related Questions