473,320 Members | 1,952 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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 3111
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
by: Chris S. | last post by:
I have a number of strings, containing wildcards (e.g. 'abc#e#' where # is anything), which I want to match with a test string (e.g 'abcdef'). What would be the best way for me to store my strings...
13
by: Hako | last post by:
I try this command: >>> import string >>> string.atoi('78',16) 120 this is 120 not 4E. Someone can tell me how to convert a decimal number to hex number? Can print A, B, C,DEF. Thank you.
6
by: Niyazi | last post by:
Hi all, What is fastest way removing duplicated value from string array using vb.net? Here is what currently I am doing but the the array contains over 16000 items. And it just do it in 10 or...
2
by: Tom Grove | last post by:
I have a server program that I am writing an interface to and it returns data in a perl dictionary. Is there a nice way to convert this to something useful in Python? Here is some sample data:...
15
by: manstey | last post by:
Hi, I have a text file called a.txt: # comments I read it using this:
3
by: aking | last post by:
Dear Python people, im a newbie to python and here...so hello! Im trying to iterate through values in a dictionary so i can find the closest value and then extract the key for that...
6
by: buzzweetman | last post by:
Many times I have a Dictionary<string, SomeTypeand need to get the list of keys out of it as a List<string>, to pass to a another method that expects a List<string>. I often do the following: ...
5
by: linnorm | last post by:
I've got a bit of code which has a dictionary nested within another dictionary. I'm trying to print out specific values from the inner dict in a formatted string and I'm running into a roadblock. ...
35
by: Abandoned | last post by:
I want to convert a string to command.. For example i have a string: a="" I want to do this list.. How can i do ?
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.