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

M

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

Thanks, Matthew

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

Jorge Godoy

manstey said:
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 <[email protected]>

"Quidquid latine dictum sit, altum sonatur."
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.
 
H

Heiko Wundram

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.
 
V

vbgunz

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 :)
 
M

manstey

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

Duncan Booth

manstey said:
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.
 
A

Aahz

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 /')")
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,298
Messages
2,571,542
Members
48,281
Latest member
Vaughn0875

Latest Threads

Top