Search code examples
pythonlistdictionaryordereddictionary

Accessing inner ordered dictionaries returned by simple-salesforce


I am working with simple-salesforce to query salesforce via Python. My query returns an ordereddict in the following format

OrderedDict([('totalSize', 1), ('done', True), ('records', [OrderedDict([('attributes', OrderedDict([('type', 'Case'), ('url', 'www.blah.com')])), ('Number', '6904'), ('Severity', 'P1'), ('Product__c', 'd231'), ('Status', 'Available'), ('Case_Comments__r', OrderedDict([('totalSize', 1), ('done', True), ('records', [OrderedDict([('attributes', OrderedDict([('type', 'Comment__c'), ('url', 'www.blah.com')])), ('CreatedDate', '2019-11-05T12:10:06.000+0000'), ('Text__c', 'dummy text'), ('Created_By_Name', 'TEST USER')])])]))])])])

I want to pull out specific data but I am having issues accessing the inner ordered dict. For example I can get 'Number' and 'Severity' by doing the following

list1 = [(record['Number'], record['Severity']) for record in data['records']]

But I also need to access 'Comment_c', i've tried the below but its failing.

list1 = [(record['Number'], record['Severity'], record['Case_Comments__r']['records']['Text__c']) for record in data['records']]

It fails with "TypeError: list indices must be integers or slices, not str"


Solution

  • As you can see, record['Case_Comments__r']['records'] is a list of OrderedDicts:

    ('records', [OrderedDict(...), ...])
    

    So it's not possible to index this list with a string like record['Case_Comments__r']['records']['Text__c'] - you'll need to loop over the list and extract data from each OrderedDict:

    ..., record['Severity'], [comment['Text__c'] for comment in record['Case_Comments__r']['records']]