DBA108642
DBA108642

Reputation: 2112

Python efficiently getting a specific value from a list of dictionaries

I am using an API to get results from a database that is returned in JSON format. I'm then trying to just extract certain keys/values and append them to a blank list. The field I want is eissn and the API returns results like this:

[
{'type': 'doi', 'id': '10.16472/j.chinatobacco.2017.045'}, 
{'type': 'pissn', 'id': '1004-5708'}, 
{'type': 'eissn', 'id': '1004-5708'}
]

I want to extract the eissn id which i have tried using this code:

deissnlist = []
for i in range(0,lengthD):
    deissnlist.append(doajresult[i]['bibjson']['identifier'][3] 
    ['id'])

Where lengthD/i are the number of results returned from the API. The problem is that the eissn ID is not always the 3rd dictionary in the list. Is there any way I can search the tuples and only get the eissn ID without using another for loop (and thus going from O(n) to O(n^2)? The expected output is just the single value of the eissn id (in this case 1004-5708)

I tried converting the list to a dictionary but that didn't work because it treated each tuple as it's own dictionary. Thanks!

Upvotes: 0

Views: 109

Answers (1)

SmokeRaven667
SmokeRaven667

Reputation: 111

I may have misunderstood question and over simplified; but, if you are looking to simply extract a list of the ids from that sample input, this is how I would do it:

input = [
    {'type': 'doi', 'id': '10.16472/j.chinatobacco.2017.045'},
    {'type': 'pissn', 'id': '1004-5708'},
    {'type': 'eissn', 'id': '1004-5708'}
]

result = [x.get('id') for x in input]

print(result)

['10.16472/j.chinatobacco.2017.045', '1004-5708', '1004-5708']

Or for just the ids where type is eissn:

result = [x.get('id') for x in input if x.get('type') == 'eissn']

Upvotes: 1

Related Questions