Python检查大型嵌套字典中是否存在键

2024-09-29 17:14:55 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我有一个大型嵌套字典,其结构如下:

dic = {Review0: [{'there': 1, 'good': 3, 'news': 4, 'bad': 4, 'first': 3}], 
        Review1: [{'roomat': 1, 'recent': 1, 'bought': 1, 'explor': 1, 'sport': 1, 'suv': 2, 'realli': 3, 'nice': 4}],
        Review2: [{'found': 2, 'pregnanc': 2, 'also': 1, 'nice': 1, 'explor': 1, 'result': 2}]}

因此,为了查看Review0中的键,我可以像这样通过字典dic[0]进行索引

我想找到一种方法在嵌套字典中循环,以检查从Review0ReviewN之间是否存在键,因此,例如,如果我想查找单词pregnanc,它将在Review2中找到它并返回True

有什么想法吗


Tags: 字典结构firstnewsbadtheregoodnice
1条回答
网友
1楼 · 发布于 2024-09-29 17:14:55

def yourfunc(dic):
    for key, value in dic.items() :
        if 'pregnanc' in value[0] :
            return True


data = {'Review0': [{'there': 1, 'good': 3, 'news': 4, 'bad': 4, 'first': 3}], 
        'Review1': [{'roomat': 1, 'recent': 1, 'bought': 1, 'explor': 1, 'sport': 1, 'suv': 2, 'realli': 3, 'nice': 4}],
        'Review2': [{'found': 2, 'pregnanc': 2, 'also': 1, 'nice': 1, 'explor': 1, 'result': 2}]}



print (yourfunc(data))



或者,如果您的“评论”可能有多个项目:

def yourfunc(dic):
    for key, value in dic.items() :
        for item in value :
            if 'pregnanc' in item :
                return True

如果这不是你要找的,请告诉我

相关问题 更多 >

    热门问题