Search code examples
pythonpython-2.7ironpythonrevit-apirevitpythonshell

Create nested dictionaries during for loop


I have created a list during a for loop which works well but I want create a dictionary instead.

from System.Collections.Generic import List

#Collector
viewPorts = list(FilteredElementCollector(doc).OfClass(Viewport))

#create a dictionary
viewPortDict = {}

#add Sheet Number, View Name and boxoutline to dictionary
for vp in viewPorts:
    sheet = doc.GetElement(vp.SheetId)
    view = doc.GetElement(vp.ViewId)
    vbox = vp.GetBoxOutline()
    viewPortDict = {view.ViewName : {'sheetNum': sheet.SheetNumber, 'viewBox' : vbox}}

print(viewPortDict)

The output from this is as follows:

{'STEEL NOTES': {'viewBox': <Autodesk.Revit.DB.Outline object at 0x000000000000065A [Autodesk.Revit.DB.Outline]>, 'sheetNum': 'A0.07'}}

Which the structure is perfect but I want it to grab everything as while it does the for loop it seems to stop on the first loop. Why is that? And how can I get it to keep the loop going?

I have tried various things like creating another list of keys called "Keys" and list of values called "viewPortList" like:

dict.fromkeys(Keys,  viewPortList)

But I always have the same problem I am not able to iterate over all elements. For full disclosure I am successful when I create a list instead. Here is what that looks like.

from System.Collections.Generic import List

#Collector
viewPorts = list(FilteredElementCollector(doc).OfClass(Viewport))

#create a dictionary
viewPortList = []

#add Sheet Number, View Name and boxoutline to dictionary
for vp in viewPorts:
    sheet = doc.GetElement(vp.SheetId)
    view = doc.GetElement(vp.ViewId)
    vbox = vp.GetBoxOutline()
    viewPortList.append([sheet.SheetNumber, view.ViewName, vbox])

print(viewPortList)

Which works fine and prints the below (only portion of a long list)

[['A0.01', 'APPLICABLE CODES', <Autodesk.Revit.DB.Outline object at 0x000000000000060D [Autodesk.Revit.DB.Outline]>], ['A0.02', etc.]

But I want a dictionary instead. Any help would be appreciated. Thanks!


Solution

  • In your list example, you are appending to the list. In your dictionary example, you are creating a new dictionary each time (thus removing the data from previous iterations of the loop). You can do the equivalent of appending to it as well by just assigning to a particular key in the existing dictionary.

    viewPortDict[view.ViewName] = {'sheetNum': sheet.SheetNumber, 'viewBox' : vbox}