【问题标题】:Match a variable against second level in a dictionary将变量与字典中的第二级匹配
【发布时间】:2018-04-01 01:15:53
【问题描述】:

我正在尝试通过字典的第二级来简化我的迭代。

我知道这适用于简单列表:

if new not in existing_list:
    dosomestuff

有没有机会为每个条目看起来像这样的字典 y 做类似的事情?

{'fields':
    {'ID': 123, 'name': 'test'},
 'otherfield': 'value'
}

我需要做的是将一个变量(我们称之为x)与每个y['fields']['ID'] 进行比较。目前我只是在遍历y,但我认为必须有更聪明的方法来找到匹配项。

【问题讨论】:

  • 不,你必须自己迭代它。
  • json.dumps()将你的字典序列化为字符串,并使用RegEx在字符串中查找子字符串

标签: python dictionary search


【解决方案1】:

为什么不创建以 ID 为键的字典呢?

d = {143:
         {‘name‘: ‘test'},
     545:
         {'name': 'another test'},
}

【讨论】:

    【解决方案2】:

    您可以创建您正在像列表一样执行此操作的错觉,但您必须遍历 dict 值。这是一种方法。

    mydict = {'fields': {'id': 123, 'name': 'value'}, 'fields2': 'test'}
    
    test_id = 123
    
    if test_id in (level2['id'] for level2 in mydict.values()):
        print("success: value found")
    else:
        print("The value does not exist")
    # Output: success: value found
    

    【讨论】:

      【解决方案3】:

      要在 1 行中检测给定的 inner_key 是否存在 inner_value,试试这个:

      my_dict= {'fields': {'ID': 123, 'name': 'test'},
                'otherfield': 'value'}
      
      inner_key, inner_value = 'ID', 123
      
      print(inner_value in [val.get(inner_key) for val in my_dict.values() if isinstance(val, dict)])
      # True
      

      请注意,如果 inner_key 不在内部字典中,get() 方法将保护您免于崩溃;
      isinstance() 函数 - 如果 my_dict.values() 中不仅有字典。

      【讨论】:

        【解决方案4】:

        我正在考虑使用列表推导来探索字典并构建要查找的每个相关字段的列表,例如['fields']['ID'],然后使用您已经提到的if x in list。这很简单,易于阅读,并且可以通过最少的修改进行调整以涵盖不同的领域。

        >>> MyDict = {}
        >>> MyDict["entry1"] = {'fields':{'ID': 123, 'name': 'test'},'otherfield': 'value' }
        >>> MyDict["entry2"] = {'fields':{'ID': 456, 'name': 'test2'},'otherfield': 'value2' }
        >>> x = 123
        >>> if x in [v['fields']['ID'] for v in MyDict.values()]:
        ...   print("found x")
        ...
        found x
        >>> x = 789
        >>> if x in [v['fields']['ID'] for v in MyDict.values()]:
        ...   print("found x")
        ...
        >>>
        

        【讨论】:

          【解决方案5】:

          'ID' 是一个列表吗?怎么样:

          dictionary = {'fields':
              {'ID': [123,456], 'name': 'test'},
              'otherfield': 'value'}
          item = 789
          if item != dictionary['fields']['ID']:
              print('Hurra!')
          

          或者对不同的数据类型使用另一种比较方法。

          如果你不知道你需要哪个一级字段:

          if item not in (dictionary[field]['ID'] for field in dictionary.keys()):
              print('Hurra!')
          

          【讨论】:

            【解决方案6】:

            其他人提供了一些不错的选择,所以我想我会列出一些你可能会选择使用的不同的东西:

            (重用用户示例)

            >>> MyDict = {}
            >>> MyDict["entry1"] = {'fields':{'ID': 123, 'name': 'test'},'otherfield': 'value' }
            >>> MyDict["entry2"] = {'fields':{'ID': 456, 'name': 'test2'},'otherfield': 'value2' }
            >>> for v in map(lambda x: x['ID'], 
                             filter(lambda x: isinstance(x, dict) and 'ID' in x,
                                    sum(map(lambda x:list(x.values()),
                                            list(MyDict.values())), 
                                        []))):
            ...     v
            ...
            123
            456
            

            为了解释这一点,从最里面的函数向外移动:

            1. innermost map 创建一个包含 N 个条目的列表,其中 N 是 顶级字典中的项目,每个条目都是值的列表 您在上面显示的 dict 格式的每个项目。因此,一个列表 列表。
            2. 将列表列表汇总为单个列表
            3. 带有“ID”键的字典过滤列表
            4. 仅从每个此类 dict 中获取“ID”值

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-06-30
              • 1970-01-01
              • 2021-11-09
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多