I'm using the configparser library in python to manage my configuration files.
But, I can't find a method to store and retrieve tuples data-structure through it.
My data is a dictionary of tuples.
name_mapper = {
0 = (0, 0)
1 = (0, 1)
2 = (0, 2)
3 = (1, 0)
4 = (1, 1)
5 = (1, 2)
6 = (2, 0)
7 = (2, 1)
8 = (2, 2)
9 = (3, 0)
10 = (3, 1)
11 = (3, 2)
}
When I write this dictionary via configparser, everything becomes a string.
myconfig.ini
[NAME_MAPPER]
0 = (0, 0)
1 = (0, 1)
2 = (0, 2)
3 = (1, 0)
4 = (1, 1)
5 = (1, 2)
6 = (2, 0)
7 = (2, 1)
8 = (2, 2)
9 = (3, 0)
10 = (3, 1)
11 = (3, 2)
Now, on reading the "my_config.ini"
config = configparser.ConfigParser()
config.read('config_params.ini')
name_mapper = dict(config['NAME_MAPPER'])
But, the dictionary no longer holds tuples, its just tuple formatted as string.
name_mapper = {
'0' = '(0, 0)'
'1' = '(0, 1)'
'2' = '(0, 2)'
'3' = '(1, 0)'
'4' = '(1, 1)'
'5' = '(1, 2)'
'6' = '(2, 0)'
'7' = '(2, 1)'
'8' = '(2, 2)'
'9' = '(3, 0)'
'10' = '(3, 1)'
'11' = '(3, 2)'
}
I figured out a way to correct this by using ast.literal_eval method.
from ast import literal_eval
new_name_mapper = dict()
for each in name_mapper:
new_name_mapper[int(each)] = literal_eval(name_mapper[each])
Now, new_name_mapper is correctly formatted.
name_mapper = {
0 = (0, 0)
1 = (0, 1)
2 = (0, 2)
3 = (1, 0)
4 = (1, 1)
5 = (1, 2)
6 = (2, 0)
7 = (2, 1)
8 = (2, 2)
9 = (3, 0)
10 = (3, 1)
11 = (3, 2)
}
But I'm sure, its not the best approach. Anyone got better & more pythonic ideas.