I have following List:
lst = [
{'Title1': {'Link': 'ZbELsW_tyWA', 'Episode': 'Episode Name'}},
{'Title2': {'Link': 'ZbELsW_tyWA', 'Episode': 'Episode Name2'}},
]
Now I want to search list by word Title1
How to get values of Link and Episode of certain key
Using a list comprehension to produce all matches:
[d[searchtitle] for d in lst if searchtitle in d]
where searchtitle
contains 'Title1'
. The result is a list of matching dictionaries.
Finding the first match only:
next((d[searchtitle] for d in lst if searchtitle in d), None)
which returns None
if there is no match, or a dictionary with the matching key in it.
Demo:
>>> lst = [
... {'Title1': {'Link': 'ZbELsW_tyWA', 'Episode': 'Episode Name'}},
... {'Title2': {'Link': 'ZbELsW_tyWA', 'Episode': 'Episode Name2'}},
... ]
>>> searchtitle = 'Title1'
>>> [d[searchtitle] for d in lst if searchtitle in d]
[{'Episode': 'Episode Name', 'Link': 'ZbELsW_tyWA'}]
>>> next((d[searchtitle] for d in lst if searchtitle in d), None)
{'Episode': 'Episode Name', 'Link': 'ZbELsW_tyWA'}
Instead of storing each title as a separate dictionary in a list, your search would be much simpler if you just stored each title as a key in one dictionary:
titles = {
'Title1': {'Link': 'ZbELsW_tyWA', 'Episode': 'Episode Name'},
'Title2': {'Link': 'ZbELsW_tyWA', 'Episode': 'Episode Name2'},
}
as now all you have to do to get the nested dictionary is directly reference the title key:
titles['Title1']
Provided your titles are unique.
You can do something like this
for item in lst:
for key,value in item.iteritems():
if key == "Title1":
link = value["Link"]
episode = value["Episode"]
You can use the filter function. The first argument to the function is a function which would help filter the list. The function we need here needs to check if 'Title1' exists in the dictionary. So this expression would give you your answer :
filter(lambda x : 'Title1' in x, lst)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.