python中dict中的键操作

python中dict中的键操作,python,dictionary,Python,Dictionary,在python中,给定一个dict的dict,比如: example = {0: {}, 1: {'foo': 0}, 2: {'foo': 1}, 3: {'foo':0, 'bar':1}, 4: {'bar':0}} 一个特定的键可能存储在一个或多个内部字典中,我想找到与该键相关的外部键和内部值 显然,只需在外键上迭代即可: value = 'foo' for outer_key in example: if value in example[outer_key]:

在python中,给定一个dict的dict,比如:

example = {0: {}, 1: {'foo': 0}, 2: {'foo': 1}, 3: {'foo':0, 'bar':1}, 4: {'bar':0}}
一个特定的键可能存储在一个或多个内部字典中,我想找到与该键相关的外部键和内部值

显然,只需在外键上迭代即可:

value = 'foo'
for outer_key in example:
    if value in example[outer_key]:
        do_things()
这是一个很好的方法吗?我在这个结构上遇到了几个变体,当您需要内部键而不一定知道它们或它们在哪里时,这看起来很尴尬


我遗漏了什么吗?

要稍微更具python风格,您可能需要迭代示例中的项目:


在字典中找到与某个值相关联的键的唯一方法是迭代字典。很抱歉,我知道没有其他方法。

在您的示例中,与例如“foo”相关联的外部键和内部值是什么?为什么不重新设计您的数据结构,以便首先基于内部键进行查找?其他人的包。在这里,我想找出键1的foo值为0,键2的foo值为1,键3的foo值为0。
for outer_key, inner_dict in example.items():
    if value in inner_dict:
        do_things()