the code is able to read the values of the first key but not the second key onwards.
#join_tables = {'table_e_input_cols': [' e.rowkey', ' e.branchsequencenumber'], 'table_e1_input_cols': [' e1.branchsequencenumber']}
i=0
for k,v in join_tables.items():
print(table_e_input_cols[i].split(sep='.'))
print(table_e1_input_cols[i].split(sep='.'))
i = i 1
Error that am getting is:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/tmp/ipykernel_31619/2960019421.py in <cell line: 20>()
20 for k,v in join_tables.items():
21 print(table_e_input_cols[i].split(sep='.'))
---> 22 print(table_e1_input_cols[i].split(sep='.'))
23 i = i 1
24 #print(k)
NameError: name 'table_e1_input_cols' is not defined
CodePudding user response:
When I try to uncomment the first line and run your code I get the following error:
NameError: name 'table_e_input_cols' is not defined
Most likely that had been defined somewhere else earlier in your code, which is why you're not getting an error for the first key.
As you are already iterating over the key and values it would be easier to print out the values as such:
join_tables = {'table_e_input_cols': [' e.rowkey', ' e.branchsequencenumber'], 'table_e1_input_cols': [' e1.branchsequencenumber', ' e1.ranchsequencenumber']}
for k,v in join_tables.items():
print(f"Key is {key} and value is {v}")
If you want to iterate over every value independently:
join_tables = {'table_e_input_cols': [' e.rowkey', ' e.branchsequencenumber'], 'table_e1_input_cols': [' e1.branchsequencenumber', ' e1.ranchsequencenumber']}
for k,v in join_tables.items():
for index, item in enumerate(v):
print(f"Key is {key} and index {index} of value is {item}")
CodePudding user response:
When you use the syntax for k,v in join_tables.items():
the variables you have available to you in the for loop are ONLY k
(the key) and v
(the value) of each of the k-v pairs in the dict. So trying to use the actual name in the loop is not possible, python only knows k and v.
The other issue is that each value is an array and you're trying to split an array at a .
and this is not going to be possible, you need to iterate over the array, not the dictionary.
Based on the clarification in the comment:
{k:[item.split('.')[1] for item in v] for k,v in join_tables.items()}
This puts it back into a dictionary bc there's no super clean way to turn a string into a variable name in python, but it should give you the format you want for the arrays.
To get the desired printout:
for k,v in join_tables.items():
print(f"{k} = {[item.split('.')[1] for item in v]}")