473,663 Members | 2,854 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to convert a String to a Dictionary?

21 New Member
I have new to python programming.

I have sucessfully converted a dictionary into a string.
but i want to know how can convert the string back to the dictionary.

let us say that 'd' is dictionary

>>>from cStringIO import StringIO
>>> d={'a':'google' , 'b':80, 'c':'string'}
>>> sio = StringIO()
>>> for item in d.iteritems():
... sio.write('%s, %s / ' %item)

>>> sio.getvalue()
a, google / c, string / b, 80

i have stored this value into a variable.

i want convert back this string into dictionary. how can i do this..

Plz help me out with this........... .
thxs in advance........
Feb 24 '09 #1
7 36054
bvdet
2,851 Recognized Expert Moderator Specialist
You can accomplish this by parsing the string.
Expand|Select|Wrap|Line Numbers
  1. items = [s for s in sio.getvalue().split(' / ') if s]
  2. dd = {}
  3. for item in items:
  4.     key,value = item.split(', ')
  5.     dd[key] = value
  6.  
  7. print dd
Output:
Expand|Select|Wrap|Line Numbers
  1. >>> {'a': 'google', 'c': 'string', 'b': '80'}
  2. >>> 
Feb 24 '09 #2
neeru29
21 New Member
thanks for the help dude....
Feb 25 '09 #3
sharat87
6 New Member
if you are saving the dictionary for later use (writing the string to a file and later reading it and reconstructing the dictionary...)

you may want to look at a serialization pattern like the pickling library.

regards,
sharat87
Feb 27 '09 #4
neeru29
21 New Member
thxs,..

But i'm trying to store the dictionary to database, but the database doesn't support to store the dictionary. as i had to convert the dictionary to string...
Feb 27 '09 #5
sharat87
6 New Member
if that's what you want, I suggest you take at look at how you can use the pickling library... you do something like this...

import pickle as pk
d={'a':'google' , 'b':80, 'c':'string'}
d_str = pk.dumps(d)
# put the string d_str into the database...
# get the string from the database and do
d = pk.loads(d_str)
# and there you have your dictionary back

i did not test the above code.. but it will be something like that..
in my opinion, it will be much easier for you to use pickling... but if you are going to use those strings for humans to read.. then forget it! :)
Feb 27 '09 #6
neeru29
21 New Member
no, these values are not used for the human reading........ ..
By using the pickling can I store the dictionary into the database......
Feb 27 '09 #7
sharat87
6 New Member
yes, in the example I showed you in my previous post... you just store the d_str string into the database... that's the string you will ever need.

using dumps(d, protocol=1) will give smaller strings, but will have binary data... i am not sure if those can be written to a databse.. but the code in my above post should work just fine

Note: i did not test it.. so if u have any more problems, just drop in here :)
Feb 27 '09 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

6
37218
by: Byron | last post by:
Hello, I am a newbie and would like to know if it is possible to convert a string back to a dictionary? For example, I can convert a dictionary to a string by doing this: >>> names = {"Candy" : 2.95, "Popcorn" : 4.95} >>> strNames = str(names) >>> print strNames
7
3134
by: manstey | last post by:
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
7
8711
by: Wilson | last post by:
Hi, How do get the Dictioanry object from FiedlInfo ? my code : fieldInfo = this.GetType().GetField("dictioanry1"); ??Dictionary<string, string> dicTemp1 = (Dictionary<string, string>)fieldInfo; Thanks Wilson
4
1921
by: James Page | last post by:
Hi all I have a shopping cart object which I'd like to send the contents via an e-mail. I get an error saying 'hybridDictionary' cannot be converted to string. Does anyone know how to do this or point me in the right direction? Thanks
6
46179
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)
15
17731
GTXY20
by: GTXY20 | last post by:
Hi, I have the following in a text file: 1,a 1,b 1,b 2,a 2,c 2,a
3
1707
by: Ameet Nanda | last post by:
Hi All, I access net using a proxy, which I have to authenticate everytime I try to access net from my system. Now when I use urllib2.urlopen(url) , I cant get ahead. I must provide proxy authentication , I tried reading docs online which speak of something called as FancyUrlOpener. Now i want to hardcode my username and password inside the script or somehow save it. How do I go ahead with that ??
35
4903
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 ?
1
8675
by: alex21 | last post by:
Ok i am trying to use a Linq query to access a dictionary. public static Dictionary<string, Client> Clients = new Dictionary<string, Client>();Using this Linq query: IEnumerable<Staff> loginquery = from staff in Database.Staff where staff.Value.Passcode == txt_password.Text select staff;but i get the error Error 2 Cannot implicitly convert type...
0
8436
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
8548
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,...
0
8634
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6186
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
5657
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4349
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2763
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
2000
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1757
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.