473,503 Members | 1,666 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

parsing a dictionary from a string

Hello list,

I could use some help extracting the keys/values of a list of
dictionaries from a string that is just the str() representation of the
list (the problem is related to some flat file format I'm using for file
IO).

Example:
>>s = str(dict_list)
s
'[{0: [2], 1: []}, {0: [], 1: [], 2: []}, {0: [1, 2]}]'

Then, what I want to do is to reconstruct dict_list given s.
Now, one possible solution would be
>>dict_list = eval(s)
but since the content of s cannot be blindly trusted I`d rather not do
it that way. Basically my question is whether there is another solution
which is simpler than using regular expressions.

Best,
Benjamin
Dec 15 '06 #1
2 2211
"Benjamin Georgi" <ge****@molgen.mpg.dewrote in message
news:ma***************************************@pyt hon.org...
Hello list,

I could use some help extracting the keys/values of a list of dictionaries
from a string that is just the str() representation of the list (the
problem is related to some flat file format I'm using for file IO).

Example:
>s = str(dict_list)
s
'[{0: [2], 1: []}, {0: [], 1: [], 2: []}, {0: [1, 2]}]'
Pyparsing comes with a working example that will parse strings representing
lists, even if they are nested. This is actually more complex than the
example you've given - none of your lists is nested. Here is that example,
adapted to handle dict elements, too.

-- Paul
(The pyparsing home page/wiki is at pyparsing.wikispaces.com.)
from pyparsing import *

cvtInt = lambda toks: int(toks[0])
cvtReal = lambda toks: float(toks[0])
cvtTuple = lambda toks : tuple(toks.asList())
cvtDict = lambda toks: dict(toks.asList())

# define punctuation as suppressed literals
lparen,rparen,lbrack,rbrack,lbrace,rbrace,colon = \
map(Suppress,"()[]{}:")

integer = Combine(Optional(oneOf("+ -")) + Word(nums))\
.setName("integer")\
.setParseAction( cvtInt )
real = Combine(Optional(oneOf("+ -")) + Word(nums) + "." +
Optional(Word(nums)))\
.setName("real")\
.setParseAction( cvtReal )
tupleStr = Forward()
listStr = Forward()
dictStr = Forward()

listItem = real|integer|quotedString.setParseAction(removeQuo tes)| \
Group(listStr) | tupleStr | dictStr

tupleStr << ( Suppress("(") + Optional(delimitedList(listItem)) +
Optional(Suppress(",")) + Suppress(")") )
tupleStr.setParseAction( cvtTuple )

listStr << (lbrack + Optional(delimitedList(listItem) +
Optional(Suppress(","))) + rbrack)

dictEntry = Group( listItem + colon + listItem )
dictStr << (lbrace + Optional(delimitedList(dictEntry) + \
Optional(Suppress(","))) + rbrace)
dictStr.setParseAction( cvtDict )

tests = """['a', 100, ('A', [101,102]), 3.14, [ +2.718, 'xyzzy', -1.414] ]
[{0: [2], 1: []}, {0: [], 1: [], 2: []}, {0: [1, 2]}]"""

for test in tests.split("\n"):
print "Test:", test.strip()
result = listStr.parseString(test)
print "Result:", result
for dd in result:
if isinstance(dd,dict): print dd.items()
print

Prints:
Test: ['a', 100, ('A', [101,102]), 3.14, [ +2.718, 'xyzzy', -1.414] ]
Result: ['a', 100, ('A', [101, 102]), 3.1400000000000001, [2.718,
'xyzzy', -1.4139999999999999]]

Test: [{0: [2], 1: []}, {0: [], 1: [], 2: []}, {0: [1, 2]}]
Result: [{0: [2], 1: []}, {0: [], 1: [], 2: []}, {0: [1, 2]}]
[(0, [2]), (1, [])]
[(0, []), (1, []), (2, [])]
[(0, [1, 2])]


Dec 16 '06 #2
Benjamin Georgi wrote:
I could use some help extracting the keys/values of a list of
dictionaries from a string that is just the str() representation of the
list (the problem is related to some flat file format I'm using for file
IO).

Example:
>>s = str(dict_list)
>>s
'[{0: [2], 1: []}, {0: [], 1: [], 2: []}, {0: [1, 2]}]'

Then, what I want to do is to reconstruct dict_list given s.
Now, one possible solution would be
>>dict_list = eval(s)

but since the content of s cannot be blindly trusted I`d rather not do
it that way. Basically my question is whether there is another solution
which is simpler than using regular expressions.
Michael Spencer has published a simple eval() that only allows constant
expressions:

http://aspn.activestate.com/ASPN/Coo.../Recipe/364469

Peter
Dec 16 '06 #3

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

Similar topics

4
3808
by: Fuzzyman | last post by:
There have been a couple of config file 'systems' announced recently, that focus on building more powerful and complex configuration files. ConfigObj is a module to enable you to much more *simply*...
8
4196
by: Anders Eriksson | last post by:
Hello! I want to extract some info from a some specific HTML pages, Microsofts International Word list (e.g. http://msdn.microsoft.com/library/en-us/dnwue/html/swe_word_list.htm). I want to...
2
2709
by: quadric | last post by:
Hi, I would like to pass a dictionary from my Python code to my Python extension, extract various values from the dictionary (from within the extension) , modify the values for the relevant...
4
4268
by: meldrape | last post by:
Hello, I need to parse a long string into no more than 30 character chunks, but I also need to leave the words intact. Right now, I am using: For intStart = 1 to Len(strOriginal) by 30...
6
2030
by: supercomputer | last post by:
I am using this function to parse data I have stored in an array. This is what the array looks like: , , , , , , , , , , , , , , , , , , , , , , , ] This is the code to parse the array:
1
9237
by: john wright | last post by:
I have a dictionary oject I created and I want to bind a listbox to it. I am including the code for the dictionary object. Here is the error I am getting: "System.Exception: Complex...
3
2503
by: Rich Shepard | last post by:
I need to learn how to process a byte stream from a form reader where each pair of bytes has meaning according to lookup dictionaries, then use the values to build an array of rows inserted into a...
3
2200
by: JamesB | last post by:
I have a config screen in my app that updates a dictionary<key,value>. I want to store a copy of this before going into the config screen so if the user wants to cancel all their changes I can...
3
1867
by: Damon Getsman | last post by:
Okay so I'm writing a script in python right now as a dirty fix for a problem we're having at work.. Unfortunately this is the first really non-trivial script that I've had to work with in python...
1
2266
by: sachin2 | last post by:
I am using 3 types of dictionaries. 1) Dictionary<string, string > d = new Dictionary<string, string>(); 2) Dictionary<string, List<string>> d = new Dictionary<string, List<string>>(); 3)...
0
7203
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,...
0
7087
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...
0
7334
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
5579
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4675
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...
0
3156
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1514
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 ...
1
737
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
383
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...

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.