Home > OS >  How do a return a subset of a dictionary based on a search string?
How do a return a subset of a dictionary based on a search string?

Time:10-21

I have a dictionary with a list of file locations

dict1 = {'news1':'link1','news2':'link2','sports1':'link3','weather1':'link4'}

Now I want to search for a string and return a new dictionary with only the relevant key value pairs. Something like

searchstring = 'news'
dict2 = if searchstring in dict1

dict2 = {'news1':'link1','news2':'link2'}

Any help would be appreciated!

CodePudding user response:

You can this with dictionary comprehension,

In [1]: {k:v for k,v in dict1.items() if 'news' in k}
Out[1]: {'news1': 'link1', 'news2': 'link2'}

CodePudding user response:

I assume you are using Python3

dict2 = dict()
for k in dict1.keys():
    if dict1[k] == searchstring:
         dict2[k] = searchstring

Not elegant but should do what you want to do.

  • Related