473,705 Members | 6,816 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3140
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(stri ngdictionary):
''' alpha! convert a string dictionary to a real dictionary.'''
x = str(stringdicti onary[1:-1].split(':'))
res = {}
for index, keyval in enumerate(x.spl it(',')):
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************ **********@38g2 000cwa.googlegr oups.com>,
manstey <ma*****@csu.ed u.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**@pythoncra ft.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
2432
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 so lookup is as fast as possible?
13
41814
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
6109
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 more minutes. 'REMOVE DUBLICATED VALUE FROM ARRAY +++++++++++++++++ Dim col As New Scripting.Dictionary Dim ii As Integer = 0
2
3588
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: 200 data follow { Calendar = { Access = { anyone = lr;};
15
3662
by: manstey | last post by:
Hi, I have a text file called a.txt: # comments I read it using this:
3
2924
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 value....what ive done so far: def pcloop(dictionary, exvalue): z = dictionary.itervalues() y = z - exvalue
6
46185
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: <BEGIN CODE> List<stringkeyNameList = new List<string>(); foreach (string keyName in this.myDictionary.Keys)
5
5577
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. I can't figure out how to get a value from the inner dict into the string. To make this even more complicated this is being compiled into a large string including other parts of the outer dict. mydict = {'inner_dict':{'Value1':1, 'Value2':2},...
35
4912
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
8690
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9274
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9034
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6606
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4440
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4704
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3138
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2491
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2083
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.