Pythonic方法检查列表中的元素是否包含在密钥字典中

时间:2015-10-27 16:35:32

标签: python dictionary

我有这样的映射关键字。

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']

有更好的方法吗?

5 个答案:

答案 0 :(得分:6)

您可以使用intersection标签和词典键:

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

部分匹配更新:

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

答案 1 :(得分:1)

>>> [categories_mapping[l] for l in labels if l in categories_mapping]
['Technology']

答案 2 :(得分:0)

你可以摆脱外循环:

for l in labels:
    if l in categories_mapping:
        cats.append(categories_mapping[l])

或者作为列表comp:

 cats = [v for k, v in categories_mapping if k in l]

答案 3 :(得分:0)

>>> 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']
>>> cats = []
>>> for l in labels:
    if l in categories_mapping:
        cats.append(categories_mapping[l])
>>> cats
['Technology']

答案 4 :(得分:0)

cats = [v for k, v in categories_mapping.items() if k in labels]