Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading