Let's say I have a dictionary called my_dic:
my_dict = {'a': {'spam': {'foo': None, 'bar': None, 'baz': None},'eggs': None}, 'b': {'ham': None}}
Then if I input spam
, it should return a
, and if I input bar
it should return spam
. If I input b
, it should return None
. Basically getting the parent of the dictionary.
How would I go about doing this?
CodePudding user response:
A simple recursive function, which returns the current key if needle in v
is true; needle in v
simply testing if the key exists in the associated value:
my_dict = {'a': {'spam': {'foo': None, 'bar': None, 'baz': None},'eggs': None}, 'b': {'ham': None}}
def get_parent_key(d: dict, needle: str):
for k, v in d.items():
if isinstance(v, dict):
if needle in v:
return k
if found := get_parent_key(v, needle):
return found
print(get_parent_key(my_dict, 'bar'))
CodePudding user response:
To check if a key exists in a dictionary and get its corresponding value, you can use the in keyword and the .get()
method.
Here's an example:
my_dict = {'a': {'spam': {'foo': None, 'bar': None, 'baz': None},'eggs'}, 'b': {'ham'}}
# Check if 'spam' is a key in my_dict and get its value
if 'spam' in my_dict:
print(my_dict['spam']) # Output: {'foo': None, 'bar': None, 'baz': None}
else:
print('Key not found')
# Check if 'bar' is a key in my_dict and get its value
if 'bar' in my_dict:
print(my_dict['bar']) # Output: Key not found
else:
print('Key not found')
# Use .get() to check if 'b' is a key in my_dict and get its value
value = my_dict.get('b')
if value is not None:
print(value) # Output: {'ham'}
else:
print('Key not found')