bottega
bottega

Reputation: 133

Convert string with [key]:[value] to dictionary

I'm trying to convert the following string(MULTI LINE) to dictionary in python3+:

props_str ="
[persist.sys.bootupvolume]: [0]
[persist.sys.dalvik.vm.lib.2]: [li]
[persist.sys.device_provisioned]: [1]
[persist.sys.displayinset.top]: [0]
[persist.sys.isolated_storage]: [true]
[persist.sys.locale]: [en-US]
[persist.sys.phonelock.mode]: [0]
[persist.sys.sf.color_saturation]: [1.0]
[persist.sys.sf.native_mode]: [1]
[persist.sys.timezone]: []"

Currently I'm using regular expression to convert above expression into a list, then convert the list to dictionary.

c = compile(r"\[(.*?)\]")
props_list = c.findall(props_str)

it = iter(props_list)
prop_dict = dict(zip(it, it))

With this method, sometimes I miss some key:value. I'm looking for an easier way to convert that.

Let's assume that our string has one line break between one [key]: \n [value]

props_str ="\
[persist.sys.bootupvolume]: [0]\
[persist.sys.dalvik.vm.lib.2]: [li]\
[persist.sys.device_provisioned]: [1]\
[persist.sys.displayinset.top]: [0]\
[persist.sys.isolated_storage]: [true]\
[persist.sys.locale]: \
[en-US]\
[persist.sys.phonelock.mode]: [0]\
[persist.sys.sf.color_saturation]: [1.0]\
[persist.sys.sf.native_mode]: [1]\
[persist.sys.timezone]: []\
[persist.sys.boot.reason]: []\
[persist.sys.boot.reason.history]: [reboot,hardware_reset,4831146 \
reboot,ota,1586292448 \
bootloader,4766793  \
reboot,4766775]"

Output will be:

{
   'persist.sys.bootupvolume': '0',
   'persist.sys.dalvik.vm.lib.2': 'li', 
   'persist.sys.device_provisioned': '1', 
   'persist.sys.displayinset.top': '0', 
   'persist.sys.isolated_storage': 'true', 
   'persist.sys.locale': 'en-US', 
   'persist.sys.phonelock.mode': '0', 
   'persist.sys.sf.color_saturation': '1.0', 
   'persist.sys.sf.native_mode': '1', 
   'persist.sys.timezone': ''
}

Notice: It will be missing 'persist.sys.boot.reason.history' propertie because of the multiple \n between same key:value. Also persist.sys.boot.reason was also not converted. Not sure why.

Upvotes: 0

Views: 222

Answers (1)

Saurabh P Bhandari
Saurabh P Bhandari

Reputation: 6742

This one-liner should do it.

prop_dict = dict((k[1: -1], v[1: -1]) for k, v in (item.split(': ') for item in props_str.split('\n')[1:]))

This assumes that there is a line break between each key-value pair.

It also assumes that the first line doesn't start with a key-value pair. If it does, just replace props_str.split('\n')[1:] with props_str.split('\n').

Approach above is similar to the one taken in this answer.

Upvotes: 1

Related Questions