Join table to Python DYNAMO

Hi, I’m having difficulty creating a script where I can associate these two pieces of information, I’m not able to get the values ​​from the tables

You need to iterate through your lists. Right now you’re comparing cabos and circuitos (lists) to the numeric and string values in your loop.

What is the exact situation you’re trying to solve here? It seems like there may be a better solution for comparing a bunch of values.

Hi Nick_Boyts

the idea would be like this, when the cables are 2.5 and the circuit is “F+N+T”, the result would be #2.5(2.5)T2.5, but I’m not able to extract this information into Python

But where do these values come from? Is there a pattern to the outcome? Could they be created on the fly or is it a specific dictionary of values? Would a dictionary work? Is cabos always going to have a 2.5 value or are there other values besides empty/null?

I would create the database, the gauge of the cables can vary and this data comes from the electrical project that I made as an example just to formulate the idea of ​​the script, I was able to run it using the 2.5 cables, for the rest I would just replicate the same idea within the script itself

the initial idea, I was using a parameter within the electrical panel table, I’ll send it to you as an attachment, but I ran into a problem, where the formula didn’t compare numbers with letters and thus couldn’t get the exact result, I was told to use the dynamo
Captura de tela 2024-01-09 135736

1 Like

Dictionaries might be best but you could always write out all the conditions like you did above. You could split them into two conditions though, one for cabos and one for circuitos. Using elif in that case would also help.

How would this look in Python?

I wanted each row of the table to come out like this

1 = #2.5(2.5)T2.5
2 = 2#2.5(2.5)T2.5
3 = 3#2.5(-)T2.5
4 = 2#2.5(-)T2.5

It depends on which method you go with. Your initial code is correct except that when you call the function you supply to lists when the function is defined with single values. You just need a loop to iterate through each value in the lists.

How do I do this loop? Would you be able to help me?

Try doing a little research yourself first. There are plenty of topics here on the forum that answer this already. If you run into any specific issues you can let us know.

Could you at least help me with the links? I’m really lost, I’ve already searched a lot on the internet and so far I haven’t found anything that could help me, this is my last attempt

Have you searched the forum itself though? Even posts that just use lists in python will be helpful because it will show you the method for dealing with lists. Here are a couple topics I found after just a brief search:

How to deal with list in python? - Dynamo (dynamobim.com)
Python Lists - Expected Element got List - Dynamo (dynamobim.com)

This one specifically for zipping lists:

You could use a dictionary as a look up table using list index to match diameters

dia_cabos = [1.5, 2.5, 4.0, 6.0, 10, 16, 25, 35, 50, 70, 95, 120, 240]
dict_ciruitos = {"2F+T": ["2#1,5(-)T1,5", "2#2,5(-)T2,5", "2#4,0(-)T4,0", ...],
                "F+N+T": ["#1,5(1,5)T1,5", "#2,5(2,5)T2,5", "#4,0(4,0)T4,0", ...],
                ...
                }

def gerar_saida(cabos, circuitos):
    if cabos in dia_cabos and circuitos in dict_ciruitos: 
        return dict_ciruitos[circuitos][dia_cabos.index(cabos)]
    return "Erro"

Crash course in loops if it helps below. I usually give this to my colleagues and it tends to sink in with some practice of the concepts I use as examples:

Also in your script you can change all but the first ‘if’ to ‘elif’ to create a staged logic process where it tries each step until it reaches the else step. Using return at each step also technically works, but if/elif is a useful structure to get used to in Python I think.

1 Like

Hi,
here, 2 solutions with Tables Datas (pandas and .Net DataTable)

pycode with pandas

# Load the Python Standard and DesignScript Libraries
import sys
import clr
clr.AddReference('Python.Included')
import Python.Included as pyInc
path_py3_lib = pyInc.Installer.EmbeddedPythonHome
sys.path.append(path_py3_lib + r'\Lib\site-packages')
import pandas as pd

def get_saida(row):
    n = row['circuit'][0] if row['circuit'][0].isdigit() else ""
    t = row['cable'] if "N" in row['circuit'] else "-"
    return "{0}#{1}({2})T{1}".format(n, row['cable'], t)

cables = [2.5, 4.0, 4.0, 2.5, 2.5]
circuits = ["2F+T", "2F+T", "2F+N+T", "F+N+T", "3F+N+T"]
data_rows = zip(cables, circuits)

df = pd.DataFrame(data_rows, columns = ['cable', 'circuit'])
df['saida'] =  df.apply(get_saida, axis=1)

OUT = ['',repr(df)]
pycode with .Net DataTable
import sys
import clr
import System
from System import IntPtr, Array

clr.AddReference('System.Data')
from System.Data import *

class CustomDataTable(DataTable):
    """A custom DataTable class with additional functionalities"""
    def __new__(cls):
        return super(DataTable, cls).__new__(cls)

    def __init__(self):
        pass

    @staticmethod
    def FromArray(lstdata, tableName=""):
        dataTable = CustomDataTable()
        dataTable.TableName = tableName
        # create columns
        for idx, item in enumerate(lstdata[0]):
            dataTable.Columns.Add(item)
        # add rows
        for sublst_values in lstdata[1:]:
            a = Array.CreateInstance(System.Object, System.Int32(len(sublst_values)))
            for i, val in enumerate(sublst_values):
                a[i] = val
            dataTable.Rows.Add(*a)
        return dataTable
        
    def add_saida(self):
        # sub function
        def get_saida(row):
            n = row['circuit'][0] if row['circuit'][0].isdigit() else ""
            t = row['cable'] if "N" in row['circuit'] else "-"
            return "{0}#{1}({2})T{1}".format(n, row['cable'], t)
        # main function to add column
        self.Columns.Add('saida', System.String)
        for row in self.Rows:
            row["saida"] = get_saida(row)
        return self
        
    def __repr__(self):
        value =  "\t\t".join([col.ColumnName for col in list(self.Columns)]) + "\n"
        for row in self.Rows:
            value += "\t\t".join([str(i) for i in row.ItemArray]) + "\n"
        return value

cables = ['cable',2.5, 4.0, 4.0, 2.5, 2.5]
circuits = ['circuit', "2F+T", "2F+T", "2F+N+T", "F+N+T", "3F+N+T"]

dt = CustomDataTable.FromArray(list(zip(cables, circuits)))
dt.add_saida()
OUT = ['',repr(dt)]
4 Likes

Could you use this script to get the information from this table?

You’re going to have to put in some effort yourself. There have already been multiple options provided to you. This is not a forum for asking people to do your work for you.

2 Likes


Hello, I managed to create the loop taking from a table, when I tried using both tables, it was going wrong, if anyone could help me, I would be very grateful, as I don’t have much skill in Python

Some comments

  • Missing variable IN for Cabos
  • You can access lists directly rather than iterating over a range and using indexes
  • Types have to match string == string, number == number, a string will not match a number
  • OUT is a special variable in the Dynamo python interpreter, so it is traditional to work with other variables and assign them to OUT at the completion of the code

Revised code

import sys
import clr  # not required

# not required as we are not using any Dynamo geometry
clr.AddReference("ProtoGeometry")
from Autodesk.DesignScript.Geometry import *

Circuitos = IN[0]  # <-- index 0 of IN, string values
Cabos = IN[1]  # <-- index 1 of IN, number values

output = []
for circuito in Circuitos:  # Access each item in the list - no indexing required
    for cabo in Cabos:
        if circuito == "F+N+T" and cabo == 2.5:  # Match to type
            output.append("#2,5(2.5)T2,5")
        else:
            output.append(False)

OUT = output