简体   繁体   中英

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

How can I return "True" or "False" if 2 consecutive strings are in a dictionary key that is a tuple/triple?

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

I need an expression like:

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

You can do it with nested for loops:

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

Then you can customize return values how you prefer

You could pair elements for each key in the dictionary and then check if any of those pairs equals your desired result, eg:

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}

this seems to work fine

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM