Posts Tagged ‘OrderedDict’

Convert a nested OrderedDict to normal dict

You have a nested OrderedDict object and you want to convert it to a normal dict.

Today I was playing with the configparser module. It reads an .ini file and builds a dict-like object. However, I prefer normal dict objects. With a configparser object’s “._sections” you can access the underlying dictionary object, but it’s a nested OrderedDict object.


; preferences.ini

onekey = "value in some words"

resolution = '1024 x 768'
import configparser
from pprint import pprint

config = configparser.ConfigParser()"preferences.ini")

Sample output:

OrderedDict([('GENERAL', OrderedDict([('onekey', '"value in some words"')])),
             ('SETTINGS', OrderedDict([('resolution', "'1024 x 768'")]))])

JSON to the rescue! Convert the nested OrderedDict to json, thus you lose the order. Then, convert the json back to a dictionary. Voilá, you have a plain dict object.

    def to_dict(self, config):
        Nested OrderedDict to normal dict.
        return json.loads(json.dumps(config))


{'GENERAL': {'onekey': '"value in some words"'},
 'SETTINGS': {'resolution': "'1024 x 768'"}}

As you can see, quotes around string values are kept by configparser. If you want to remove them, see my previous post.

I found this solution here @ SO.