473,802 Members | 1,960 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 2225
"Benjamin Georgi" <ge****@molgen. mpg.dewrote in message
news:ma******** *************** *************** *@python.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.wikis paces.com.)
from pyparsing import *

cvtInt = lambda toks: int(toks[0])
cvtReal = lambda toks: float(toks[0])
cvtTuple = lambda toks : tuple(toks.asLi st())
cvtDict = lambda toks: dict(toks.asLis t())

# define punctuation as suppressed literals
lparen,rparen,l brack,rbrack,lb race,rbrace,col on = \
map(Suppress,"( )[]{}:")

integer = Combine(Optiona l(oneOf("+ -")) + Word(nums))\
.setName("integ er")\
.setParseAction ( cvtInt )
real = Combine(Optiona l(oneOf("+ -")) + Word(nums) + "." +
Optional(Word(n ums)))\
.setName("real" )\
.setParseAction ( cvtReal )
tupleStr = Forward()
listStr = Forward()
dictStr = Forward()

listItem = real|integer|qu otedString.setP arseAction(remo veQuotes)| \
Group(listStr) | tupleStr | dictStr

tupleStr << ( Suppress("(") + Optional(delimi tedList(listIte m)) +
Optional(Suppre ss(",")) + Suppress(")") )
tupleStr.setPar seAction( cvtTuple )

listStr << (lbrack + Optional(delimi tedList(listIte m) +
Optional(Suppre ss(","))) + rbrack)

dictEntry = Group( listItem + colon + listItem )
dictStr << (lbrace + Optional(delimi tedList(dictEnt ry) + \
Optional(Suppre ss(","))) + rbrace)
dictStr.setPars eAction( 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.parseSt ring(test)
print "Result:", result
for dd in result:
if isinstance(dd,d ict): 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.1400000000000 001, [2.718,
'xyzzy', -1.4139999999999 999]]

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
3831
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* access config files. This is version 3, which is a big overhaul. It extends ConfigObj to reading config files with sections and various other simplifications. I find ConfigObj extremely easy to use and use it for reading config files and data...
8
4240
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 take all the words, both English and the other language and create a dictionary. so that I can look up About and get Om as the answer. How is the best way to do this?
2
2725
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 keys and return the modified dictionary to Python. Can someone point me to an example of what the C code might look like to do this?
4
4286
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 strPrint = Mid$(strOriginal, intStart, 30) Print #detailFile, Tab(1), intStart, Tab(4), strPrint Next intStart
6
2050
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
9264
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 DataBinding accepts as a data source either an IList or an IListSource at System.Windows.Forms.ListControl.set_DataSource(Object value)
3
2523
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 sqlite3 database table. Here's the context: The OMR card reader sends a stream of 69 bytes over the serial line; the last byte is a carriage return ('\r') indicating the end of record. Three pairs (in specific positions at the beginning of the...
3
2216
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 simply set the working copies to be the backup. So, in my code, before the config screen is shown, I do this: Dictionary<string, myClassTempDic = MainDic;
3
1882
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 and the book that I have on it really kind of sucks. I'm having an issue parsing lines of 'last' output that I have stored in a /tmp file. The first time it does a .readline() I get the full line of output, which I'm then able to split() and...
1
2279
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) Dictionary<string, Dictionary<string, string>> d = new Dictionary<string, Dictionary<string, string>>(); Now I am using GetDictionaryType Function where I an sending a dictionary object. In GetDictionaryType() I want to find out which dictionary...
0
9562
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
10542
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...
0
10068
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...
0
9119
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7600
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
6840
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
5496
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
5625
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3795
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.