1

Slightly different use case than this post: Convert a String representation of a Dictionary to a dictionary?

The difference being I am reading in from an excel spreadsheet so my string looks like this:

'{numerator: BV, denominator: Price}'

I don't have quotation marks around the keys or values. Wondering if there is some easy way to convert this into a dictionary. The usage of ast won't work I don't think.

I've done this, but I doubt this is the best way. Any suggestions?

test_params = '{numerator: BV, denominator: Price}'
comma_split = test_params.replace("{", "").replace("}", "").split(",")

reconstructed_params = {}

for i in comma_split:
    splitted = i.split(":")
    splitted[0] = splitted[0].strip()
    splitted[1] = splitted[1].strip()
    reconstructed_params[splitted[0]] = splitted[1]

print(reconstructed_params)

{'numerator': 'BV', 'denominator': 'Price'}

A nice easy way would be great. There will also be times where my values are lists, but one thing at a time I suppose.

WhitneyChia
  • 746
  • 2
  • 11
  • 28
  • If it doesn't conform to any sort of established standard, then it's highly unlikely there'll be an "easy" way to do it. It'll have to be something like you have. – glibdud Mar 20 '19 at 19:57

1 Answers1

1

Te quotes are here to protect the keys & values from other quotes, colons, braces, etc. Now, if keys are values are alphanumeric, you could apply a regular expression to add the quotes, then use ast.literal_eval

import re,ast

d = ast.literal_eval(re.sub('(\w+)',r'"\1"','{numerator: BV, denominator: Price}'))

>>> type(d)
<class 'dict'>
>>> d
{'denominator': 'Price', 'numerator': 'BV'}

This solution is fairly generic with the hypothesis taken, as it can decode nested dictionaries as well.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219