How to get a dict lookup by adjacent value

Question:

I have the following object:

ancestorTitles': [{
    u 'contentType': u 'SERIES',
    u 'titleId': u 'B00ERMZZRA',
    u 'title': u 'Criminal Minds'
}, {
    u 'contentType': u 'SEASON',
    u 'number': 10,
    u 'titleId': u 'B00SSFZWB6',
    u 'title': u 'Criminal Minds Staffel 10'
}]

How would I get the titleId of the "SERIES" here(“B00ERMZZRA”)? My current approach uses a for loop.

Asked By: David542

||

Answers:

>>> [item.get('titleId') for item in t if item.get('contentType') == 'SERIES'][0]
'B00ERMZZRA'
Answered By: David542

I reverse engineered your answer to make a reusable function

def get_dict_by_value(dict_list, field, value):
    """returns dictionary with specific value in given field"""
    for d in dict_list:
        if d.get(field) == value:
            return d

The function returns the entire dictionary from which you can get the value(s) you want

list = [{
    'contentType': 'SERIES',
    'titleId': 'B00ERMZZRA',
    'title': 'Criminal Minds'
}, {
    'contentType': 'SEASON',
    'number': 10,
    'titleId': 'B00SSFZWB6',
    'title': 'Criminal Minds Staffel 10'
}]


single_dict = get_dict_by_value(list, 'contentType', 'SERIES')

print(single_dict)

>>> { 'contentType': 'SERIES', 'titleId': 'B00ERMZZRA', 'title': 'Criminal Minds' }

Get any value you want like this

print single_dict.get('contentType')

>>> SERIES


print single_dict.get('titleId')

>>> B00ERMZZRA
Answered By: Dawoodjee
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.