Unable to extract key value from dictionaries present in double list in python

Viewed 87

Unable to extract key value from dictionaries present in double list in python

I have 2d list

print(sent[:2])

output is :

[[{'label': 'negative', 'score': '0.99'}]
 [{'label': 'positive', 'score': '0.96'}]]

I'm trying to extract label key values i.e. negative and positive

I tried running the below code, but it's returning an empty list

sentiment = [i['label'] for i in sent if 'label' in i]
print(sentiment)

output is :

[]

I'm expecting the output to be:

['negative', 'positive']
3 Answers

First of all, each dict being a singleton-list in unnecessary.
But that being a given, the right way to access a dictionary field is by the key. So how about -

sentiment = [x[0]['label'] for x in sent]
print(sentiment)

If your if clause is due to not always having a label key, then just add that if in the list comprehension -

sentiment = [x[0]['label'] for x in sent if 'label' in x[0].keys()]

And if you want a default value for non-existing labels, then using .get is very useful -

sentiment = [x[0].get('label', 'No label') for x in sent]

You have a doubly nested list, with each sublist only having one item. Therefore, you need to access the first element of the sublist from your list comprehension:

sent = [[{'label': 'negative', 'score': '0.99'}], [{'label': 'positive', 'score': '0.96'}]]
sentiment = [i[0]['label'] for i in sent if 'label' in i[0]]
print(sentiment)  # ['negative', 'positive']

If this is something you need to do quite often, we can have this as a simple function.

sent = [[{'label': 'negative', 'score': '0.99'}],
 [{'label': 'positive', 'score': '0.96'}]]

def doubleListKeyExtractor(inputList:list, labelStr: str):
    cur = 0
    output = []

    while cur < len(t):
        for each in t[cur]:
            output.append(each[labelStr])
        cur += 1
    
    return output

print(doubleListKeyExtractor(sent,'label'))
print(doubleListKeyExtractor(sent,'score'))

//Results
['negative', 'positive']
['0.99', '0.96']
Related