473,385 Members | 1,506 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,385 software developers and data experts.

StringToDict and DictToString

I made this tonight, after discovering how bad it is to use eval() in
a server program. If someone knows of a better method, let me know!

import types

'''
Convert a string to a dict, or a dict to a string.
Not that comprehensive - it only handles strings, ints,
longs, floats, and None, but it's safer than using 'eval'
and trying to restrict the execution environment!
--Kamilche

Sample output:
--------------
orig dict: {'int': 1, 'none': None, 'float': 1.0,
'string': 'string', 'long': 12345678901234567890L}
to string: ' int 1 none None float 1.0 string string long
12345678901234567890'
to dict: {'int': 1, 'none': None, 'float': 1.0,
'string': 'string', 'long': 12345678901234567890L}

'''

def StringToDict(s):
'''
Convert a string to a dict.
The first char of the string is the delimiter for the items.
Try to parse it, and on failure, return an empty dict.
'''
if type(s) != types.StringType:
raise Exception("Arg to StringToDict must be a string!")
try:
if len(s) < 4:
return {}
delim = s[0]
tokens = s.split(delim)
i = 1
max = len(tokens) - 1
d = {}
while i < max:
key = tokens[i]
value = StringToValue(tokens[i + 1])
d[key] = value
i += 2
return d
except:
return {}

def DictToString(d, delim = '\t'):
'''
Convert a dict to a string. If the str() of any key or value
in the dict contains the delimiter, raise an error. Otherwise,
insert the delimiter into the first character of the string.
'''
tokens = []
if type(d) != types.DictType:
raise Exception("Argument must be a dict!")
if len(d) == 0:
return ''
if len(delim) != 1:
raise Exception("Delimiter must be a single character!")
tokens.append('')
for key, value in d.items():
key = str(key)
value = str(value)
if delim in key or delim in value:
raise Exception("Pick a different delimiter for
DictToString, your data uses %s!" % delim)
tokens.append(key)
tokens.append(value)
return delim.join(tokens)

def StringToValue(s):
" Convert a string to the 'best guess' type"
if type(s) != type(""):
return s
if len(s) == 0:
return s
if s in ('None', 'none'):
return None
if (s[0] in "+-0123456789.") and ("." in s):
try:
v = float(s)
return v
except:
pass
if s[0] in "+-0123456789":
try:
v = int(s)
return v
except:
try:
v = long(s)
return v
except:
pass
return s

def test(**d):
print "orig dict:", d
s = DictToString(d, ' ')
print "to string: '" + s + "'"
print "to dict: ", StringToDict(s)
print

def main():
test()
test(string = 'string', int = 1, float = 1.0, long =
12345678901234567890, none = None)

if __name__ == "__main__":
main()
Jul 18 '05 #1
0 931

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Kamilche | last post by:
I have a code snippet here that prints a dict in an arbitrary order. (Certain keys first, with rest appearing in sorted order). I didn't want to subclass dict, that's error-prone, and overkill for...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.