[英]Python get key of a value inside a nested dictionary
Let's say I have a dictionary called my_dic:假设我有一本名为 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
.然后如果我输入
spam
,它应该返回a
,如果我输入bar
它应该返回spam
。 If I input b
, it should return None
.如果我输入
b
,它应该返回None
。 Basically getting the parent of the dictionary.基本上得到字典的父级。
How would I go about doing this?我将如何 go 这样做?
A simple recursive function, which returns the current key if needle in v
is true;一个简单的递归 function,如果
needle in v
为真,则返回当前键; needle in v
simply testing if the key exists in the associated value: needle in v
只是测试键是否存在于关联值中:
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'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.