python - Pythonic way to check if element in a list contains in key dictionary -


i have mapping keywords this.

categories_mapping = {         'comics': 'comic books',         'cartoons': 'comic books',         'manga': 'comic books',         'video , computer games': 'video games',         'role playing games': 'video games',         'immigration': 'immigration',         'police': 'police',         'environmental': 'environment',         'celebrity fan , gossip': 'celebrity',         'space , technology': 'nasa / space',         'movies , tv': 'tv , movies',         'elections': 'elections',         'referendums': 'elections',         'sex': 'sex',         'music': 'music',         'technology , computing': 'technology'} 

and list this.

labels = ['technology , computing', 'arts , technology'] 

i want return value of dictionary if words in list in key of dictionary.

this i've come think that's not pythonic.

cats = [] k,v in categories_mapping.items():     l in labels:         if k in l:             cats.append(v) return cats 

the result want ['technology']

any better way of doing this?

you can use intersection of labels , dictionary keys:

cats = [categories_mapping[key] key in set(labels).intersection(categories_mapping)] 

update partial match:

cats = [categories_mapping[key] key in categories_mapping if any(label.lower() in key.lower() label in labels)] 

Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -