mercredi 31 juillet 2019

Iterate over a nested dictionary to produce a tuple list that matches tables with the same key

I want to make a tuple list (table1, table2, Key) from a nested dictionary. I will need to match tables that have the same primary key and match tables that have the same foreign key.

I've used .items and .print(), but it doesn't give me what I want and I can't save those results as a list.

This is the code for the nested dictionary that I have to iterate over:

tables = {}
for table in table_list:
    tables[table] = {}
    tables[table]['cols'] = df_is_columns[df_is_columns.TABLE_NAME == table]['COLUMN_NAME'].tolist()
    has_constraint = False
    PK_tmp = df_is_constraints_cols[(df_is_constraints_cols.TABLE_NAME == table) &  (df_is_constraints_cols['CONSTRAINT_NAME'].str.startswith('PK'))][['CONSTRAINT_NAME', 'COLUMN_NAME']].to_dict('list')
    if(len(PK_tmp['CONSTRAINT_NAME'])):
        has_constraint = True
        tables[table]['constraints'] = {}
        tables[table]['constraints']['Primary'] = PK_tmp
    FK_tmp = df_is_constraints_cols[(df_is_constraints_cols.TABLE_NAME == table) & (df_is_constraints_cols['CONSTRAINT_NAME'].str.startswith('FK'))][['CONSTRAINT_NAME','COLUMN_NAME']].to_dict('list')
    if(len(FK_tmp['CONSTRAINT_NAME'])):
        if not has_constraint:
            tables[table]['constraints'] = {}
        tables[table]['constraints']['Foreign'] = FK_tmp

I run into errors when a Key has a "Primary", but no "Foreign" and other similar situations.

Aucun commentaire:

Enregistrer un commentaire