How to access the exported dictionary in ghPython?

Hi guys

I’d like to shed some light on this. So that you know why things are working this way. Please keep in mind: besides reasonable Python programmer goals, while using GhPython we are in Grasshopper land and are using all facilities that come from IronPython.

So, things to keep in mind:

  • A dictionary that is passed as output from a component will be seen as enumerable and will be enumerated. Grasshopper needs enumerated objects, and GhPython buffers results for Grasshopper when it sees them. When you enumerate, it is exactly the same as calling for key in dictionary: in Python. This means that only the keys will be resolved.

  • Because of what is written in the first bullet point, I believe that since ghPython cannot read dictionary as INPUT is actually an issue with the output. The data associated with the key (so-called value) is lost. If an analog to set existed in Grasshopper, but with dictionaries, I could create one when GhPython spots a dictionary, but such a construct is not present in Grasshopper right now.

  • Enumerables of enumerables will not be iterated at the second, deeper lever. This is a general Grasshopper rule that is kept in GhPython simply because of using the Grasshopper SDK. This is because Grasshopper uses data trees.

Here a simple approach for improving this: if all you want is to pass data without it being enumerated (and copied for you), you could hide it in a class. Then GhPython would have no idea about its internals, and would simple leave it up to you to keep things in sync. However, be careful never to modify the contents of the dictionary in downstream components, or things will go wrong, in a difficult-to-debug manner.

Example for a fix:

data-in-dictionary.gh (4.0 KB)

Does it help?

Giulio


Giulio Piacentino
for Robert McNeel & Associates
giulio@mcneel.com

5 Likes