首页 > 解决方案 > 根据单独的字典有条件地创建字典

问题描述

我发现了类似的问题,但大多数是针对 Python 2 及更早版本的。

我有一列有 5000 多个值,我正在用它创建一个字典。我想列出一些带有某些单词的行,如果该值不包含它,它将被保存到“其他”。

我做了以下事情:

my_groups = {
    'Group 1' : r'utilities|cleaning',
    'Group 2' : r'cooking|kitchen',
    'Group 3' : r'decorations|planning',
    'Group 4' : r'conceirge|guest|information|attendants',
    #...there are 300 groups in the dataset
}

但由于数据如此之大,我需要将这些组分为两类:前线后门。我可以:

group_cat = {
    'Frontline' : r'conceirge|guest|information|attendants|waiter|MC',
    'Backdoor' : r'utilities|cleaning|cooking|kitchen|chef|event|decorations|planning',
    #...there are 300 groups in the dataset
}

但是这个列表会很长,因为大约有 300 个不同描述的组。有没有一种方法可以让我只指定第一个并在另一个中自动分配其他?

#something like this
group_cat = {
    'Frontline' : r'conceirge|guest|information|attendants|waiter|MC',
    'Backdoor' : r'OTHER_KEYWORDS_HERE',
}

标签: pythonpython-3.xstringdictionaryjupyter-notebook

解决方案


如果我正确理解了这个问题,下面的代码应该可以工作:

代码:

my_groups = {
    'Group 1' : r'utilities|cleaning',
    'Group 2' : r'cooking|kitchen',
    'Group 3' : r'decorations|planning',
    'Group 4' : r'conceirge|guest|information|attendants',
}

group_cat = {
    'Frontline' : r'conceirge|guest|information|attendants|waiter|MC'
    }

group_cat['Backdoor'] = '|'.join(set(x 
                                     for val in my_groups.values()
                                     for x in val.split('|') 
                                     if x not in group_cat['Frontline'])
                                 )

输出:

>>> group_cat
{'Frontline': 'conceirge|guest|information|attendants|waiter|MC',
 'Backdoor': 'cooking|utilities|planning|cleaning|decorations|kitchen'}

推荐阅读