Skip to content
Advertisement

Crafting a python dictionary based on a .properties file

I want to parse a .properties-file’s keys and values into a python dictionary. The .properties-file I’m parsing uses the following syntax (keys and values are examples):

JavaScript

So each value corresponds to a key consisting of one or more levels divided with periods. The goal is to create a Python dictionary where each key is a dictionary containing its value and subkeys. The dictionary should be recursively iterable, so each level should follow the same structure.

The previous example should result in the following kind of dictionary:

JavaScript

I’m looping it with the following algorithm in python:

JavaScript

The resulting dictionary (outputDict) is missing two key-value pairs (key1.subkey1.subsubkey1=value1, key1.subkey1.subsubkey2=value2):

JavaScript

I’m pretty sure the problem is with the following row:

JavaScript

I’m replacing newObj within the dictionary with each iteration of the loop.

Is there a way to tweak this existing algorithm to make it work, and if not, how should I start over? Efficiency is not an issue, the properties-file isn’t very large.

Advertisement

Answer

I copied your function and test your code and made some changes. The below code is working fine.

JavaScript

Output is coming as:

JavaScript

Replaced your OutputDict variable with storageDict.keys() and wrote a sample main function. Try running it for yourself and see if it is working for you.

What I think is your OutputDict contains only subKeys key so the condition will always be true and you will replace the previously added dictionary with a blank dictionary.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement