0

I have a list containing several dicts. I want to store each of these dicts in a separate variable.

The data is something like:

my_list = [{'key': 'value'}, {'key' : 'value'}]

I have tried the following code.

for i in range(len(data)):
    string = 'ticket' + str(i)
    exec('eval(string) = data[i]')

However, when I run the code, it gives me the error can't assign to function call. Is there any way to get it to evaluate string and assign to that? I want it to execute something like this:

ticket1 = data[1] 
pgp
  • 83
  • 6

1 Answers1

0

A better approach is to have a dictionary of dictionaries

#List of dictionaries
my_list = [{'key': 'value'}, {'key' : 'value'}]

#Dictionary of dictionaries
dct = {'data_{}'.format(idx): item for idx, item in enumerate(my_list)}

print(dct)

#Use keys to access inner dictionary
print(dct['data_0'])

The output will be

{'data_0': {'a': 1}, 'data_1': {'b': 2}}
{'a': 1}
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40