【问题标题】:Python - Check if a key exists in a large nested dictionaryPython - 检查大型嵌套字典中是否存在键
【发布时间】:2021-02-28 15:46:39
【问题描述】:

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

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

有什么想法吗?

【问题讨论】:

    标签: python loops dictionary if-statement conditional-statements


    【解决方案1】:
    
    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
    
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2019-06-13
      • 2017-06-23
      • 1970-01-01
      • 2016-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多