Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-dimension dictionary in configparser

Is it possible to store a multi-dimensional dictionary (3 deep) using the Python 'configparser' using indentions? The work-around is to split the key values, but wanted to know if there was a clean way to import directly into a dictionary.

DOES NOT WORK - USING SUB-OPTION INDENTION IN CONFIGPARSER


    [OPTIONS]
        [SUB-OPTION]
        option1 = value1
        option2 = value2
        option3 = value3

WORKS - SPLITING USED ON SUB-OPTION VALUES


    [OPTIONS]
    SUB-OPTION  = 'option1, value1',    
                  'option2, value2',
                  'option3, value3'

DICTIONARY VALUES


    dict['OPTIONS']['SUB-OPTION'] = {
        option1 : value1,
        option2 : value2,
        option3 : value3,
    }

like image 990
NobleVision Avatar asked Apr 27 '16 15:04

NobleVision


People also ask

How do you access a multi level dictionary in Python?

Access Nested Dictionary Items You can access individual items in a nested dictionary by specifying key in multiple square brackets. If you refer to a key that is not in the nested dictionary, an exception is raised. To avoid such exception, you can use the special dictionary get() method.

What is Configparser Configparser ()?

Source code: Lib/configparser.py. This module provides the ConfigParser class which implements a basic configuration language which provides a structure similar to what's found in Microsoft Windows INI files.

Is Configparser built in Python?

configparser comes from Python 3 and as such it works well with Unicode. The library is generally cleaned up in terms of internal data storage and reading/writing files.

What is Configparser module in Python?

The configparser module from Python's standard library defines functionality for reading and writing configuration files as used by Microsoft Windows OS. Such files usually have . INI extension. The INI file consists of sections, each led by a [section] header.


1 Answers

ASAIK, there is a nested configuration file in that format.

I suggest a json like config file:

{
 "OPTIONS": {
   "SUB-OPTIONS": {
     "option1" : value1,
     "option2" : value2,
     "option3" : value3,
   }
 }
}

Then in the code use:

from ast import literal_eval
with open("filename","r") as f:
 config = literal_eval(f.read())

Edit

Alternatively, you can use YAML (with PyYAML) as a great configuration file.

The following configuration file:

option1:
    suboption1:
        value1: hello
        value2: world
    suboption2:
        value1: foo
        value2: bar

Can be parsed using:

import yaml
with open(filepath, 'r') as f:
    conf = yaml.safe_load(f)

Then you can access the data as you would in a dict:

conf['option1']['suboption1']['value1']
>> 'hello'
like image 192
Liran Funaro Avatar answered Sep 28 '22 01:09

Liran Funaro