Home > python > Convert a nested OrderedDict to normal dict

Convert a nested OrderedDict to normal dict

Problem
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.

Example:

; preferences.ini

[GENERAL]
onekey = "value in some words"

[SETTINGS]
resolution = '1024 x 768'
import configparser
from pprint import pprint

config = configparser.ConfigParser()
config.read("preferences.ini")
pprint(config._sections)

Sample output:

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

Solution
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))

Output:

{'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.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: