Archive
Posts Tagged ‘OrderedDict’
Convert a nested OrderedDict to normal dict
June 9, 2018
Leave a comment
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.
Categories: python
configparser, ini, nested dict, OrderedDict, to_dict
