【问题标题】:Python - Checking for "subdictionary"Python - 检查“子字典”
【发布时间】:2018-09-28 23:02:11
【问题描述】:
A = {
    'a': 1,
    'b': 2,
    'c': 3
}

B = {
    'a': 1,
    'b': 2,
    'c': 3,
    'd': 4
}

我的目标是检查 A 是否是 B 的“子字典”。我的意思是 A 中的每一对 key:value 都在 B 中。这是我的尝试

def is_sub_dict(first_dict, second_dict):
    for x in first_dict:
        if x not in second_dict or first_dict[x] != second_dict[x]:
            return False
    return True

is_sub_dict(A, B) #True
is_sub_dict(B, A) #False

有没有更好的方法来做到这一点?或者,也许是一种更 Pythonic 的方式,因为这看起来不像。

【问题讨论】:

    标签: python python-3.x python-2.7 dictionary key


    【解决方案1】:

    从字典元组创建一个set,然后测试该集合是否是其他项元组的子集

    def is_subset(A,B):
       return set(A.items()).issubset(B.items())
    

    创建后,set 保证非常快速的查找。

    (如果必须使用相同的A 重复操作,最好“缓存”set(A.items()) 以获得更好的性能)

    之所以有效,是因为字典的值是可散列的。如果不是,那么旧的 all(x in y for ...) 方法是另一种选择(请参阅其他答案)。

    【讨论】:

      【解决方案2】:

      看看这个

      all(item in B.items() for item in A.items())
      

      希望对你有帮助!!

      【讨论】:

        【解决方案3】:

        怎么样:

        def is_subset(a, b):
            return all(item in b for item in a)
        

        然后简单地说:

        if is_subset(A.items(), B.items()):
           # ...
        

        【讨论】:

          猜你喜欢
          • 2019-04-19
          • 1970-01-01
          • 1970-01-01
          • 2011-11-01
          • 1970-01-01
          • 2011-04-13
          • 2021-09-09
          • 1970-01-01
          • 2013-03-04
          相关资源
          最近更新 更多