我如何创建一个单独的大字典,而不是一堆小字典

时间:2012-07-06 15:08:56

标签: python pointers dictionary nested-loops

我遇到了问题。解决方案可能是直截了当但我没有看到它。下面的代码返回一堆单独的字典而不是一个大字典。然后我遍历这些小字典来提取值。问题是我宁愿通过一个LARGE字典而不是一堆小字典进行排序。 " objFunctions.getAttributes"返回一本字典。 " objFunctions.getRelationships"返回一个指针。

这是输出:     {1:值}     {2:值}     {3:值}

这就是我想要的:     {1:价值,2:价值,3:价值}

for object in objList:
   relationship = objFunctions.getRelationships(object)
   for relPtr in relationships:
      uglyDict = objFunctions.getAttributes(relPtr)

2 个答案:

答案 0 :(得分:3)

使用.update() method合并词组:

attributes = {}
for object in objList:
    relationship = objFunctions.getRelationships(object)
    for relPtr in relationships:
        attributes.update(objFunctions.getAttributes(relPtr))

请注意,如果在.getAttributes的不同调用中重复键,则最后attributes中存储的值将是为该键返回的最后一个值。

如果您不介意将值存储为列表;你必须手动将你的dicts与逐个附加的值合并到defaultdict:

from collections import defaultdict

attributes = defaultdict(list)
for object in objList:
    relationship = objFunctions.getRelationships(object)
    for relPtr in relationships:
        for key, value in objFunctions.getAttributes(relPtr):
            attributes[key].append(value)

现在,您的attributes dict将包含每个键的列表,其中包含各种值。您也可以使用集合,改为使用defaultdict(set)attributes[key].add(value)

答案 1 :(得分:1)

>>> from collections import defaultdict
>>> x = defaultdict(list)
>>> y = defaultdict(list)
>>> x[1].append("value1")
>>> x[2].append("value2")
>>> y[1].append("value3")
>>> y[2].append("value4")
>>> for k in y:
...     x[k].extend(y[k])
...
>>> print x
defaultdict(<type 'list'>, {1: ['value1', 'value3'], 2: ['value2', 'value4']})