Seungho Lee
Seungho Lee

Reputation: 1155

Checking the keys inside of the keys in dictionary

Is there a way to check the inner keys inside of the dictionary keys and if the element has the key element inside, returning the corresponding value from a dictionary.

e.g. check if there s any element that "Hello" is in the key tuple's second element, and if it exists, return the corresponding value.

d = {(1, "Hello"): "a", (2, "Bye"): "b"}
key = "Hello"
# Since "Hello" exist in d's key's element(second position), return "a"

Upvotes: 1

Views: 1498

Answers (4)

Anton vBR
Anton vBR

Reputation: 18914

Using next (which will return as soon match is found). By setting default return to None we ensure we don't get the StopIteration error and we can now go ahead and use dictionaries get function.

Note that this will in most cases be quicker than a full lookup.

key = 'Hello'
d.get(next((t for t in d if key in t), None))

Returns:

'a'

Upvotes: 4

Samantha
Samantha

Reputation: 273

Yes; however, you have to iterate over every key in your dictionary until you find the "inner key" you are looking for. The code looks like this:

d = {(1, "Hello"): "a", (2, "Bye"): "b"}
key = "Hello"

for k in d.keys():
    if key in k:
        print(d[k])

You can check if an element exists in a tuple with Python's in keyword. This allows you to check if your key is an "inner key" anywhere inside your key.

This code will print a as the output.

Upvotes: 2

Prune
Prune

Reputation: 77910

Get the list of all key tuples that contain the key; grab the first element of that list, and use it as an index to d.

>>> d = {(1, "Hello"): "a", (2, "Bye"): "b"}
>>> key = "Hello"
>>> d[[key_tuple for key_tuple in d if key in key_tuple][0]]
'a'

Upvotes: 2

jsones
jsones

Reputation: 91

You could iterate over the key tuples, check if the second value of the tuple equals what you want (e.g. "hello"), and if it does then return the value for that key. Something like this:

d = {(1, "Hello"): "a", (2, "Bye"): "b"}
key = "Hello"
for k in d:
    if k[1] == key:
        return d[k]

Upvotes: 2

Related Questions