簡體   English   中英

如何在python字典中訪問/聲明元組鍵值

[英]How to access/assert tuple key values in a python dictionary

如果兩個連續的字符串在元組/三元組的字典鍵中,如何返回“ True”或“ False”?

 d = {(1, 'a', 'b') : 2, (4, 'c', 'd'):5}

我需要一個像這樣的表達式:

return 'a', 'b' in d.keys()

您可以使用嵌套的for循環來做到這一點:

def myFunc(myDict):
    myKeys = list(myDict.keys())
    for myList in myKeys:
        myPreviousElement = None
        for myElement in myList:
            if myElement == myPreviousElement:
                return True
            myPreviousElement = myElement
    return False

d = {(1, 'a', 'a') : 2, (4, 'c', 'd'):5}
print(myFunc(d)) # True

d = {(1, 'a', 'b') : 2, (4, 'c', 'd'):5}
print(myFunc(d)) # False

然后,您可以根據自己的喜好自定義返回值

您可以為字典中每個鍵的元素配對,然后檢查這些對中的任何一個是否等於您想要的結果,例如:

d = {(1, 'a', 'b') : 2, (4, 'c', 'd'):5}

# Check for existence of any key matching criteria
any(pair == ('a', 'b') for key in d for pair in zip(key, key[1:]))
# True

# Filter out keys/values matching criteria
{k: v for k, v in d.items() if any(p == ('a', 'b') for p in zip(k, k[1:]))}
# {(1, 'a', 'b'): 2}

這似乎很好

for key in d:
        return key[1] == string_1 and key[2] == string_2

暫無
暫無

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

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