开发者

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=T开发者_Python百科rue)
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?


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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜