469,621 Members | 1,685 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,621 developers. It's quick & easy.

NEWB: how to convert a string to dict (dictionary)

Hi,

How do I convert a string like:
a="{'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'}"

into a dictionary:
b={'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'}

Thanks, Matthew

PS why in Python is it so often easy to convert one way but not the
other?

May 24 '06 #1
7 2900
manstey wrote:
Hi,

How do I convert a string like:
a="{'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'}"

into a dictionary:
b={'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'}

Thanks, Matthew

PS why in Python is it so often easy to convert one way but not the
other?


I don't belive it is Python's fault. In fact, you're going from a data
structure that contains enough information to be converted to a string in
one way -- dict to string -- while you're going from another data structure
that has no information at all about its contents on the other way --
string to dict/list/whatever.

Anyway:

In [1]:a="{'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS':
u'8'}"

In [2]:type(a)
Out[2]:<type 'str'>

In [3]:b = eval(a)

In [4]:type(b)
Out[4]:<type 'dict'>

In [5]:b
Out[5]:{'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'}
Be seeing you,
--
Jorge Godoy <go***@ieee.org>

"Quidquid latine dictum sit, altum sonatur."
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.
May 24 '06 #2
Am Mittwoch 24 Mai 2006 07:52 schrieb manstey:
Hi,

How do I convert a string like:
a="{'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'}"

into a dictionary:
b={'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'}


b = eval(a)

(if a contains a dict-repr)

--- Heiko.
May 24 '06 #3
manstey wrote:
Hi,

How do I convert a string like:
a="{'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'}"

into a dictionary:
b={'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'}


Try this recipe:
http://aspn.activestate.com/ASPN/Coo.../Recipe/364469
May 24 '06 #4
I am sure something much more elaborate will show it's face but this I
made in about 10 minutes. Didn't do much testing on it but it certainly
does convert your string modeled after a dictionary into a real
dictionary. You might wish to check against more variations and
possibilities and tweak and learn till your heart is content...

def stringDict(stringdictionary):
''' alpha! convert a string dictionary to a real dictionary.'''
x = str(stringdictionary[1:-1].split(':'))
res = {}
for index, keyval in enumerate(x.split(',')):
if index == 0:
keyval = keyval[2:]
if index % 2 == 0:
y = keyval.lstrip(" '").rstrip("'\" ")
res[y] = None
else:
z = keyval.lstrip(" \" '").rstrip("'")
res[y] = z

res[y] = z[:-2]
print res # {'syllable': "u'cv-i b.v^ y^-f", 'ketiv-qere': 'n',
'wordWTS': "u'8'"}
sd = "{'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS':
u'8'}"
stringDict(sd)

keep in mind the above code will ultimately return every value as a
substring of the main string fed in so may not be very helpful when
trying to save int's or identifiers. None the less, I hope it is useful
to some degree :)

May 24 '06 #5
Thanks. I didn't know eval could do that. But why do many posts say
they want a solution that doesn't use eval?

May 24 '06 #6
manstey wrote:
Thanks. I didn't know eval could do that. But why do many posts say
they want a solution that doesn't use eval?

Because it is a sledgehammer: capable of driving in nails or breaking
rocks. Most times people say 'I want to use eval' they are using it to
drive nails and something like 'getattr' would be more appropriate.

If you have a string which could have come from an untrusted source it can
be dangerous. Quite easily you can construct strings which will execute
arbitrary Python code.
e.g. If you are running an application on a web server and part or all of
the string has come from another system (which you don't necessarily
trust), then using eval could potentially do anything. Don't give people
you don't know a sledgehammer to use on your code.
May 25 '06 #7
In article <11**********************@38g2000cwa.googlegroups. com>,
manstey <ma*****@csu.edu.au> wrote:

Thanks. I didn't know eval could do that. But why do many posts say
they want a solution that doesn't use eval?


Because it is a security risk!

eval("os.system('rm -rf /')")
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"I saw `cout' being shifted "Hello world" times to the left and stopped
right there." --Steve Gonedes
May 25 '06 #8

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

21 posts views Thread by Chris S. | last post: by
13 posts views Thread by Hako | last post: by
2 posts views Thread by Tom Grove | last post: by
15 posts views Thread by manstey | last post: by
3 posts views Thread by aking | last post: by
5 posts views Thread by linnorm | last post: by
35 posts views Thread by Abandoned | last post: by
reply views Thread by devrayhaan | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.