将字典的字符串表示形式转换为真实字典

将字典的字符串表示形式转换为真实字典

本文介绍了将字典的字符串表示形式转换为真实字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个图像处理脚本。我需要让用户指定如何通过文本文件重新映射图像中的某些类。该文件中的语法应该是简单和不言而喻的。我想到的是让用户写字典版本的字典:

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

然后将其转换成一个真正的字典(这是缺少的链接):

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

然后,图像类的重新映射将像这样完成:

  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到原始的dims

有没有一种简单的方法来从字符串版本转换为真正的字典?你能想到用户可以使用的更简单/替代的单行语法吗?

解决方案

您可以使用:

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

请注意,这需要Python 2.6或更高版本。



另一种方法是将字符串拆分为','然后在'上分割每个片段:'并构造一个 dict 从那里:

 >>>在s.split(',')中的x的dict(map(int,x.split(':'))
{128:128,125:126,126:126,127:128}

这两个例子都假设你的初始字符串在一个名为 s

 >>> s ='125:126,126:126,127:128,128:128'


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?

解决方案

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'

这篇关于将字典的字符串表示形式转换为真实字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 20:51