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.
Answers:
>>> [item.get('titleId') for item in t if item.get('contentType') == 'SERIES'][0]
'B00ERMZZRA'
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
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.
>>> [item.get('titleId') for item in t if item.get('contentType') == 'SERIES'][0]
'B00ERMZZRA'
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