簡體   English   中英

如何檢查一個字典的所有鍵是否在另一個字典中?

[英]How to check if all keys of a dictionary present in another 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.

任何建議都會有所幫助。

set(d1) <= set(d2)

set將字典轉換為其一組鍵。 然后,我們可以使用<=檢查集合包含。

keys()簡單循環並在第二個dict檢查keys()

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

使用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

您可以使用Counter來自collections夾”模塊的Counter 更快。

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

在這方面,您可以使用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...

希望這能解決您的問題再見! 祝你一切都好!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM