【问题标题】:Manipulation of keys in dict-of-dicts in pythonpython中dict-of-dicts中键的操作
【发布时间】:2014-10-15 06:53:58
【问题描述】:

在python中,给定一个dict-of-dicts,比如:

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()

这是一种好的/Pythonic 方式吗?我在这种结构上遇到了几个变体,当您需要内部键而不必知道它们或它们在哪里时,这似乎很尴尬。

我错过了什么吗?

【问题讨论】:

  • 在您的示例中,与(例如)'foo' 关联的“外部键和内部值”是什么?为什么不首先修改您的数据结构以根据内部键查找内容?
  • 其他人的包裹。在这里,我想找出key 1的foo值为0,key 2的foo值为1,key 3的foo值为0。

标签: python dictionary


【解决方案1】:

为了更符合 Python 风格,您可能需要遍历 itemsexample

for outer_key, inner_dict in example.items():
    if value in inner_dict:
        do_things()

【讨论】:

    【解决方案2】:

    在字典中找出与值关联的键的唯一方法是遍历字典。对不起,我不知道有其他方法。

    【讨论】:

      猜你喜欢
      • 2019-08-28
      • 1970-01-01
      • 2014-12-17
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      相关资源
      最近更新 更多