【发布时间】:2015-10-27 16:35:31
【问题描述】:
我有一个这样的映射关键字。
categories_mapping = {
'comics': 'Comic Books',
'cartoons': 'Comic Books',
'manga': 'Comic Books',
'video and computer games': 'Video Games',
'role playing games': 'Video Games',
'immigration': 'Immigration',
'police': 'Police',
'environmental': 'Environment',
'celebrity fan and gossip': 'Celebrity',
'space and technology': 'NASA / Space',
'movies and tv': 'TV and Movies',
'elections': 'Elections',
'referendums': 'Elections',
'sex': 'Sex',
'music': 'Music',
'technology and computing': 'Technology'}
和这样的列表。
labels = ['technology and computing', 'arts and technology']
如果列表中的任何单词在字典的键中,我想返回字典的值。
这是我想出的,但我认为这不是很pythonic。
cats = []
for k,v in categories_mapping.items():
for l in labels:
if k in l:
cats.append(v)
return cats
我想要的结果是['Technology']
有更好的方法吗?
【问题讨论】:
-
对不起,这里的
labels是什么? -
你能显示你的预期输出吗?
-
您可能需要考虑使用frozensets 作为您的字典键。它将使查找速度更快,并更好地表示数据。
-
你的意思是
for l in labels: if k in l还是你的意思是if k in labels?
标签: python dictionary