2

ini file:

[main]
key_1=1
key_2=2
key_1=3

Python:

config_parser = ConfigParser()
config_parser.optionxform = str
config_parser.read('config.ini')
for section in config_parser.sections():
    for key in dict(config_parser.items(section)):
        print key

Result:

key_1
key_2

Expected result:

key_1
key_2
key_1

How to achieve such a result?

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
oleksii
  • 1,367
  • 2
  • 10
  • 11

1 Answers1

2

This is a problem the way the config parser in Python 2 works. The key-value pairs are converted into a dictionary. This means each key must be unique. If you have multiple keys, the "last value wins".

Trying your example in Python 3.5, gives this error message:

DuplicateOptionError: While reading from 'config.ini' [line  4]: 
option 'key_1' in section 'main' already exists

So don't use the the same key multiple times.

Fortunately, there is a backport for Python 2. Just:

pip install configparser 

This library brings the updated configparser from Python 3.5 to Python 2.6-3.5.

Now, use like this:

from configparser import ConfigParser

This is what Wikipedia says about duplicates:

Duplicate names

Most implementations only support having one property with a given name in a section. The second occurrence of a property name may cause an abort, it may be ignored (and the value discarded), or it may override the first occurrence (with the first value discarded). Some programs use duplicate property names to implement multi-valued properties.

Interpretation of multiple section declarations with the same name also varies. In some implementations, duplicate sections simply merge their properties together, as if they occurred contiguously. Others may abort, or ignore some aspect of the INI file.

Community
  • 1
  • 1
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • 2
    It's not a solution for me. The main point of this action is to check duplicates in config files and show it – oleksii Jan 14 '17 at 21:13
  • Duplicates are supposed to be an error. Are checking for erroneous ini files? – Mike Müller Jan 14 '17 at 21:21
  • Duplicates are supposed to be an error - it's not an error. ConfigParser is skipped duplicates and show only the last key-value pair. (In Python 2.7) – oleksii Jan 14 '17 at 21:24
  • The new, Python 3 version treats it as an error. This is considered an improvement. – Mike Müller Jan 14 '17 at 21:27
  • I've got your point about Python3, but this script will be running at the more than 50 servers on which other scripts are using Python2.7, and due to security policy I can't use another version of Python. So I need to find some workaround for Python2.7 – oleksii Jan 14 '17 at 22:04
  • How about the backport for Python 2? Can you install libraries? – Mike Müller Jan 14 '17 at 22:30
  • unfortunately this action also prohibited by security policy and get all approvals for install additional plugins will take a lot of time – oleksii Jan 14 '17 at 22:41