python - How to find dict value by Key in list -


i have following list:

lst = [     {'title1': {'link': 'zbelsw_tywa', 'episode': 'episode name'}},     {'title2': {'link': 'zbelsw_tywa', 'episode': 'episode name2'}}, ] 

now want search list word title1

how values of link , episode of key

using list comprehension produce matches:

[d[searchtitle] d in lst if searchtitle in d] 

where searchtitle contains 'title1'. result list of matching dictionaries.

finding first match only:

next((d[searchtitle] d in lst if searchtitle in d), none) 

which returns none if there no match, or dictionary matching key in it.

demo:

>>> lst = [ ...     {'title1': {'link': 'zbelsw_tywa', 'episode': 'episode name'}}, ...     {'title2': {'link': 'zbelsw_tywa', 'episode': 'episode name2'}}, ... ] >>> searchtitle = 'title1' >>> [d[searchtitle] d in lst if searchtitle in d] [{'episode': 'episode name', 'link': 'zbelsw_tywa'}] >>> next((d[searchtitle] d in lst if searchtitle in d), none) {'episode': 'episode name', 'link': 'zbelsw_tywa'} 

instead of storing each title separate dictionary in list, search simpler if stored each title key in one dictionary:

titles = {     'title1': {'link': 'zbelsw_tywa', 'episode': 'episode name'},     'title2': {'link': 'zbelsw_tywa', 'episode': 'episode name2'}, } 

as have nested dictionary directly reference title key:

titles['title1'] 

provided titles unique.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -