I'm trying to build a function that assign keys and values to a defaultdict in python3, but it fails in exec execution. Let's say that I need to pass several str variables as keys and other as values in a defaultdict inside:
Define a dd:
dict=dd(lambda: dd(lambda: dd(lambda: dd(list))))
Decide variables as keys:
keys_var = ['a', 'b', 'c', 'd']
Decide variables as values :
values_var = ['d', 'e', 'f', 'g' ]
Arrange values for keys :
key_for_dict = []
for value in keys_var :
value_for_keys.append( '[' + str(value) + ']' )
string_insert_keys = ''.join(key_for_dict)
it will looks like:
[a][b][c][d]
Arrange values for values insert:
values_for_dict = []
for value in values_var:
values_for_dict.append(value)
string_for_values = ', '.join(values_for_dict)
string_insert_values = "[ " + string_for_values + " ]"
it will looks like:
[ d, e, f, g ]
And now define a function to insert these keys and values in a loop (where a,b,c,d etc take different values and the final argument is a join of all these d, e, f, g )
I tried:
def riempie_dict_var( dizionario ) :
exec( dizionario + string_insert_keys + ".append('___'.join( " + string_insert_columns + "))" )
but it fails with:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'collections.defaultdict' and 'str'