Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transforming the string representation of a dictionary into a real dictionary

I am working on an image processing script. I need to let the user specify how to remap some classes in an image via a text file. The syntax in this file should be simple and self-evident. What I thought of doing is to get the user to write the string version of a dictionary:

125:126, 126:126, 127:128, 128:128

and then transform it into a real dictionary (this is the missing link):

a = {125:126, 126:126, 127:128, 128:128}

The remapping of the classes of the image would then be done like this:

u, indices = numpy.unique(image, return_inverse=True)
for i in range(0, len(u)):
    u[i] = a[u[i]]
updatedimage = u[indices]
updatedimage = numpy.resize(updatedimage, (height, width)) #Resize to original dims

Is there a simple way to do this transformation from the "string version" to a real dictionary? Can you think of an easier/alternative one-line syntax that the user could use?

like image 878
Benjamin Avatar asked Nov 08 '10 19:11

Benjamin


1 Answers

You can use ast.literal_eval:

>>> import ast
>>> ast.literal_eval('{' + s + '}')
{128: 128, 125: 126, 126: 126, 127: 128}

Note that this requires Python 2.6 or newer.

An alternative is to split the string on ',' and then split each piece on ':' and construct a dict from that:

>>> dict(map(int, x.split(':')) for x in s.split(','))
{128: 128, 125: 126, 126: 126, 127: 128}

Both examples assume that your initial string is in a variable called s:

>>> s = '125:126, 126:126, 127:128, 128:128'
like image 158
Mark Byers Avatar answered Oct 26 '22 04:10

Mark Byers