Reputation: 51
I have a config file named num_list.conf
[SMART]
LIST={
'SMART' : {813,900,907,908,909,910,911,912,918,919,920,921,928,929,930,931,938,939,940,946,947,948,949,971,980,989,998,999}
}
[GLOBE]
LIST={
'GLOBE' : {817,905,906,915,916,917,926,927,935,936,937*,975,994,996,997},
'PREPAID' : {922,923,925,932,933,934,942,943,944}
}
[SUN_CELLULAR]
LIST=
'SUN_CELLULAR' : {922,923,925,932,933,934,942,943,944}
}
How to read this dictionary type in python
Upvotes: 0
Views: 526
Reputation: 5090
There is an easier way. There exists a module named configparser but it doesn't automatically convert to dictionary. Instead you can keep the dictionary as a json string and load it like so (You will have to change the structure of config file a bit though):
Here is the file:
[SMART]
SMART = {"smart":[813,900,907,908,909,910,911,912,918,919,920,921,928,929,930,931,938,939,940,946,947,948,949,971,980,989,998,999]}
[GLOBE]
LIST={"GLOBE" : [817,905,906,915,916,917,926,927,935,936,937,975,994,996,997],"PREPAID" : [922,923,925,932,933,934,942,943,944]}
[SUN_CELLULAR]
LIST={"SUN_CELLULAR" : [922,923,925,932,933,934,942,943,944]}
Here is the python code:
>>> import configparser
>>> import json
>>> conf = configparser.ConfigParser()
>>> conf.read("config.conf.txt")
['config.conf.txt']
>>> json.loads(conf["SMART"]["SMART"])
{'smart': [813, 900, 907, 908, 909, 910, 911, 912, 918, 919, 920, 921, 928, 929, 930, 931, 938, 939, 940, 946, 947, 948,
949, 971, 980, 989, 998, 999]}
Upvotes: 0
Reputation: 246
I called your file num_list.conf and saved it in D:. You have an asterisk in one of the numbers, so I don't think converting the numbers to floating point or int would be a good idea
This should work:
results = {}
with open(r'd:\num_list.conf') as conf:
for lines in conf:
if ":" in lines:
lineval = lines.split()
name = lineval[0].replace("'","")
numbers = lineval[-1][1:-1]
numbers = numbers.split(",")
results[name]=numbers
print(results)
#result
{'SMART': ['813', '900', '907', '908', '909', '910', '911', '912', '918', '919', '920', '921', '928', '929', '930', '931', '938', '939', '940', '946', '947', '948', '949', '971', '980', '989', '998', '999'], 'SUN_CELLULAR': ['922', '923', '925', '932', '933', '934', '942', '943', '944'], 'PREPAID': ['922', '923', '925', '932', '933', '934', '942', '943', '944'], 'GLOBE': ['817', '905', '906', '915', '916', '917', '926', '927', '935', '936', '937*', '975', '994', '996', '997}']}
Upvotes: 2