如何检查一个字典的所有键是否在另一个字典中?

时间:2019-03-26 13:37:49

标签: python python-3.x dictionary

给出两个字典,我想找出第二个字典中是否存在所有键。

示例:d1 = {'a':2, 'b':3, 'c':5} d2 = {'a':2, 'b':2}

预期输出:TrueFalse

我使用交集运算来查找具有公共元素的字典,如果结果的长度等于d2的长度,则进行所需的计算。

我正在寻找一种优化的方法,因为我的数据非常大。

我有一个字符串列表(最多10 4 ),另一个列表包含给定字符串中要搜索的单词。对于每个字符串,我正在使用Counter操作来获取单词格式的字典,并且对查询字符串也采用了类似的方法。现在,我必须对照每个查询输入检查每个测试字符串。

这是我的方法:

def textQueries(sentences, queries):
    bagsofwords = [ Counter(re.findall(r'\w+', sentence)) for sentence in sentences]
    #print(bagsofwords)
    bagofqueries = [ Counter(re.findall(r'\w+', query)) for query in queries]
    #print(bagofqueries)
    si = [[]for y in range(len(queries))]
    search_count = [0]*len(bagofqueries)


for j in range(0,len(bagofqueries)):
     if search_count[j] < 10:
        boq = bagofqueries[j]
        for i in range(0,len(bagsofwords)):
            t = bagsofwords[i] & boq

            if len(t) == len(boq):
                #Doing operation.

任何建议都会有所帮助。

5 个答案:

答案 0 :(得分:2)

set(d1) <= set(d2)

set将字典转换为其一组键。然后,我们可以使用<=来检查集合包含。

答案 1 :(得分:1)

keys()上进行简单循环,并在第二个keys()中检查dict

d1 = {'a':2, 'b':3, 'c':5} 
d2 = {'a':2, 'b':2}

def all_keys(d1,d2):
    for key in d1.keys():
      if key not in d2.keys():
        return False

答案 2 :(得分:0)

使用all()

def all_keys_available(d1, d2):
    return all(k in d2 for k in d1)

用法

>>> d1 = {'a':2, 'b':3, 'c':5}
>>> d2 = {'a':2, 'b':2}
>>> all_keys_available(d1, d2)
False

答案 3 :(得分:0)

您可以从Counter模块使用collections。更快。

from collections import Counter
d1 = {'a':2, 'b':3, 'c': 2} 
d2 = {'a':2, 'b':2}
print(Counter(d1.keys()) == Counter(d2.keys())) // False

d1 = {'a':2, 'b':3} 
d2 = {'a':2, 'b':2}
print(Counter(d1.keys()) == Counter(d2.keys())) // True

答案 4 :(得分:0)

矩阵编程器这一边, 您可以使用keys()方法获取密钥,然后进行比较!

a = {'a' : 1, 'b' : 2, 'c' : 1}
b = {'a' : 1, 'b' : 2, 'c' : 1}

print(a.keys()) #By the keys() method we get all the keys of a dict like a in this case
print(b.keys()) #Just to show it...

if a.keys() == b.keys() : #Checks if the two dicts' keys match...
    print(True) #Will print true if the two dicts have the same keys
else :
    print(False)

#I would though prefer to convert them into list before comparing them that way it becomes easy for the
#interpreter to understand the code and it may not give an error at times this method may...

希望这可以解决您的问题!祝你一切都好!