【问题标题】:Have a nested dictionary in python, and would like to fine an efficient way to append to it在 python 中有一个嵌套字典,并希望有一种有效的方法来附加它
【发布时间】:2012-06-23 19:38:14
【问题描述】:

我正在寻找最好的 Pythonic 方法来做到这一点。

嵌套字典看起来像这样(主脚本):

my_dict = { test: { 
                   test_a: 'true',
                   test_b: 'true
                  }

我正在导入一个具有返回数值的函数的模块。

我正在寻找一种从模块返回的字典中追加到 my_dict 字典的方法。

即模块中的函数:

def testResults1():
  results = 3129282
  return results

def testResults2():
  results = 33920230
  return results

def combineResults():
  Would like to combine results, and return a dictionary. Dictionary returned is:
  # Looking for best way to do this.

  test_results = { 'testresults1': 3129282, 
                   'testresults2': 33920230
                  }

然后我想将 test_results 字典附加到 my_dict。 也在寻找最好的方法来做到这一点。

提前谢谢你!

【问题讨论】:

  • 为什么嵌套很重要?你希望你的新字典插入到my_dict 的“顶层”还是test 下?
  • my_dict 的最终预期值是多少?

标签: dictionary nested python


【解决方案1】:

您在寻找dict.update() 方法吗?

>>> d = {'a': 1, 'b': 2}
>>> d2 = {'c': 3}
>>> d.update(d2)
>>> d
{'a': 1, 'b': 2, 'c': 3}

【讨论】:

  • 啊..好的..这行得通..我可以使用 d.update(myfunction)。我认为这对于我问题的第二部分来说很公平。对于第一部分..您会建议在我调用的外部模块中组合字典结果吗?再次感谢您提供的信息。
  • 我正在将字典插入到 nosql 数据库中,我需要嵌套字典以进行组织。
【解决方案2】:
my_dict = {}

def testResults1():
  results = 3129282
  return results

def testResults2():
  results = 33920230
  return results

def combineResults():
  suite = [testResults1, testResults2]

  return dict((test.__name__, test()) for test in suite)  

my_dict.update(combineResults())
print my_dict

【讨论】:

    【解决方案3】:
    import collections
    my_dict = collections.defaultdict(lambda: {})
    
    def add_values(key, inner_dict):
        my_dict[key].update(inner_dict)
    

    您可以在库文档here 中阅读有关collections.defaultdict 的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多