In a file there can be several dictionaries like this
{Key11: Value11
Key12: Value12
Key13: Value13,
....
....
Key1n:Value1n}
{Key21: Value21
Key22: Value22
Key23: Value23,
....
....
Key2n:Value2n}
{Key31: Value31
Key32: Value32
Key33: Value33,
....
....
Key3n:Value3n}
.....
.....
.....
{Keyn1: Valuen1
Keyn2: Valuen2
Keyn3: Value3,
....
....
Keynn:Valuenn}
Each pair in a dictionary is separated by CRLF and in each dictionary
numbers of pairs can be different.
I need to read only the the first and the last dictionaries.Wh at is a
best solution?
Thanks
Lad 12 1611 py****@hope.cz a écrit : In a file there can be several dictionaries like this
(snip) I need to read only the the first and the last dictionaries.Wh at is a best solution?
Depends on your definition of 'best solution'.
Can your dictionaries contain dictionaries ?
If not you can read the file and cut at the first '}' and the last '{'.
The two chunks will then be a single dictionary which can be eval'd.
*However* your example above does not show ',' between all of the
pairs... but only some. This will bugger you royally (because you can't
even replace '\n' with ','). You'd then need to parse the two chunks
and correct.....
Regards,
Fuzzy http://www.voidspace.org.uk/python/index.shtml
Fuzzyman wrote: Can your dictionaries contain dictionaries ?
If not you can read the file and cut at the first '}' and the last
'{'. The two chunks will then be a single dictionary which can be eval'd.
*However* your example above does not show ',' between all of the pairs... but only some. This will bugger you royally (because you
can't even replace '\n' with ','). You'd then need to parse the two chunks and correct..... Regards,
Hi Fuzzy,
dictionaries can NOT contain dictionaries.
I re-checked and I would need only the last dictionary.
Any idea how I could do that?
Thanks
Lad.
What about the syntax ? Will it have commas in the right place ?
(never, always, or sometimes ? - sometimes is much worse than never or
always).
*damn* - problem is that '{' might appear as one of the values....
*So*... read the file in as a list of lines and strip each line.
Dictionaries will always start where '{' is the first character. Anyway
- you could always explicitly check if each line ends with a ',' and if
it doesn't add one...)
(*warning* UNTESTED) handle = open('filename' , 'r') thefile = handle.readline s() handle.close ()
dictindex = [] i = 0 while i < len(thefile)-1: if line.startswith ('{'): dictindex.appen d(i) i += 1 lastdict = ' '.join(thefile[dictindex[-1]:] print eval(lastdict)
Checking if each line ends with a ',' (except for the last line) should
be easy !
HTH
Regards,
Fuzzy http://www.voidspace.org.uk/python/index.shtml
Assumptions:
1) You actually meant to have commas between each key value pair
(which your example DOES NOT have).
2) File can be read into memory
3) All the key and value variables are actually defined in the
local namespace or they are literal values instead of references
to variables.
This works:
Key11=11
Value11='V11'
Key12=12
Value12='12'
Key13=13
Value13='V13'
Key21=21
Value21='V21'
Key22=22
Value22='V22'
Key23=32
Value23='V23'
Key31=31
Value31='V31'
Key32=32
Value32='V32'
Key33=33
Value33='V33'
testdata='''
{Key11: Value11,\n
Key12: Value12,\n
Key13: Value13}\n
{Key21: Value21,\n
Key22: Value22,
Key23: Value23}\n
{Key31: Value31,\n
Key32: Value32,\n
Key33: Value33}\n
'''
#
# Or read data from a file
#
# f=open(file, 'r')
# testdata=f.read ()
# f.close()
#
dictlist=testda ta.replace('\n' ,'').split('{')
firstdictstr='{ '+dictlist[2]
lastdictstr='{' +dictlist[-1]
firstdict=eval( firstdictstr)
lastdict=eval(l astdictstr)
print "firstdict= ", firstdict
print "lastdict=" , lastdict
firstdict=eval( firstdictstr)
lastdict=eval(l astdictstr)
Larry Bates py****@hope.cz wrote: In a file there can be several dictionaries like this {Key11: Value11 Key12: Value12 Key13: Value13, ... ... Key1n:Value1n} {Key21: Value21 Key22: Value22 Key23: Value23, ... ... Key2n:Value2n} {Key31: Value31 Key32: Value32 Key33: Value33, ... ... Key3n:Value3n} .... .... .... {Keyn1: Valuen1 Keyn2: Valuen2 Keyn3: Value3, ... ... Keynn:Valuenn}
Each pair in a dictionary is separated by CRLF and in each dictionary numbers of pairs can be different. I need to read only the the first and the last dictionaries.Wh at is a best solution? Thanks Lad
On Wed, 02 Feb 2005 02:35:03 -0800, python wrote: Each pair in a dictionary is separated by CRLF and in each dictionary numbers of pairs can be different. I need to read only the the first and the last dictionaries.Wh at is a best solution? Thanks Lad
Who cares about the best solution? Odds are, your process is disk-bound
anyhow.
Is this a thinly-veiled attempt to get someone to provide you *a*
solution, or do you already have one and you are seriously asking for a
better one? Because I'd say, take the easiest programming route: Parse the
first dict into a variable, then just loop until you run out of file,
storing a parsed dict in the "last" variable and just naturally letting
later ones overwrite earlier ones.
If you want something "best"-er than that (heh heh), you're going to have
to tell us how you are measuring better-ness. py****@hope.cz wrote: In a file there can be several dictionaries like this {Key11: Value11 Key12: Value12 Key13: Value13, ... ... Key1n:Value1n} {Key21: Value21 Key22: Value22 Key23: Value23, ... ... Key2n:Value2n} {Key31: Value31 Key32: Value32 Key33: Value33, ... ... Key3n:Value3n} .... .... .... {Keyn1: Valuen1 Keyn2: Valuen2 Keyn3: Value3, ... ... Keynn:Valuenn}
Each pair in a dictionary is separated by CRLF and in each dictionary numbers of pairs can be different. I need to read only the the first and the last dictionaries.Wh at is a best solution?
Assumption:
File is small enough to be read into memory at once. Contents of the
file have been read into the variable "testdata":
py> # your data
py> testdata="""
.... {Key11: Value11
.... Key12: Value12,
.... Key13: Value13}
.... {Key21: Value21,
.... Key22: Value22
.... Key23: Value23}
.... {Key31: Value31
.... Key32: Value32,
.... Key33: Value33}
.... """
py>
py> # get the contents of the first and last dict
py> content_strs = testdata.strip( '{}\n\t ').split('}\n{' )
py> content_strs = content_strs[0], content_strs[1]
py> print content_strs
('Key11: Value11\nKey12: Value12,\nKey13 : Value13', 'Key21:
Value21,\nKey22 : Value22\nKey23: Value23')
py>
py> # correct missing commas and add braces
py> dict_strs = ['{%s}' % s.replace('\n', ',\n').replace( ',,\n', ',\n')
.... for s in content_strs]
py> print dict_strs
['{Key11: Value11,\nKey12 : Value12,\nKey13 : Value13}', '{Key21:
Value21,\nKey22 : Value22,\nKey23 : Value23}']
py>
py> # build mapping of names to values
py> names = {}
py> for i in range(1, 4):
.... for j in range(1, 4):
.... s = '%i%i' % (i, j)
.... names['Key%s' % s] = int(s)
.... names['Value%s' % s] = 'V%s' % s
....
py>
py> # eval strings to get dicts
py> first_dict, last_dict = [eval(s, names) for s in dict_strs]
py> first_dict
{11: 'V11', 12: 'V12', 13: 'V13'}
py> last_dict
{21: 'V21', 22: 'V22', 23: 'V23'} dictionaries can NOT contain dictionaries.
Who told you this?
In my python, they can.
d1={1:"one"} d2={2:"two"} d1
{1: 'one'} d2
{2: 'two'} d3={3:d2} d3
{3: {2: 'two'}} py****@hope.cz wrote: Fuzzyman wrote: Can your dictionaries contain dictionaries ? Hi Fuzzy, dictionaries can NOT contain dictionaries. I re-checked and I would need only the last dictionary. Any idea how I could do that? Thanks Lad. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Matt Wade |
last post by:
A new PHP Coding Contest has been released at Codewalkers.com. The latest
challenge is to play a variation of the Numbers Game as seen on the UK
television show Countdown. Basically, you are supplied with 6 numbers and a
target number. Your program should manipulate the 6 numbers with basic
arithmetic operators to reach the target number. More information can be had
at:
http://codewalkers.com/php-contest.php
|
by: vpd |
last post by:
hi,
I want some help in organising an online programming contest. Is there
a ready made solution available in PHP or even Perl which I could use?
The contest is supposed to be based on C programming and the solutions
submitted by the participants must be compiled, executed and the marks
shall be allocated automatically.
I want some urgent help as the contest is supposed to be organised in
just a couple of days. Any suggestions and...
|
by: Robby Findler |
last post by:
Think your favorite programming language is the best one out
there? Put it to the test in this year's International Conference
on Functional Programming's annual Programming Contest. The
contest is coming up in a little under 4 weeks and we have just
released more information (including a live cd, mailing list, and
prize details) to the web page, at:
http://icfpc.plt-scheme.org/
This year's competition rewards programmers who can plan...
|
by: hicinbothem |
last post by:
GLOSSY: The Summer Programmer Of The Month Contest is underway!
Deadline is September 30, 2005
http://dinsights.com/POTM
--------------------------------------------------------------------------------
I love taking digital pictures, but that nice glossy photo paper
is expensive! So when my lovely wife asks for prints of a bunch
of pictures, I always try and fit them onto a single piece of paper.
The summer POTM challenges you to...
|
by: Brian Quinlan |
last post by:
I've decided that it would be be fun to host a weekly Python programming
contest. The focus will be on algorithms that require a bit of thought
to design but not much code to implement.
I'm doing to judge the solutions based on execution speed. It sucks but
that is the easiest important consideration to objectively measure. I'll
also indicated which solutions I think are good examples of Python
design. Hopefully, people's solutions can...
| |
by: ziliath |
last post by:
I recently tried out the Google "top coder" contest, as a C++
coder. I noticed immediately that they expected me to know STL.
To which I say, what the fuck?!
I may be missing something, but at what point when learning C++
was I supposed to have picked up STL? I ask because at every
job I've had, and every job interview for that matter, whenever
STL comes up it's not I, but a manager who says effectively
yuck, we don't use that crap.
|
by: Catherine Chronaki |
last post by:
The OpenECG programming contest is now open to submissions. Prizes
total 10,000 Euros.
For more information, visit the OpenECG portal:
http://www.openecg.net
and click on Programming Contest. Questions may be addressed to
contest@openecg.net.
|
by: virtualadepts |
last post by:
This contest is open to everyone who knows C++. To enter all you need
to do is take the Boyer-Moore String Search Algorithm, as it is
written in C, and make the fastest running C++ program you can out of
it. I'm going to try to write code myself, and if you can beet me,
and your code executes faster, then you win a free I-Pod. My I-Pod is
used, but it comes jam packed with songs I've been listening to. So
take a crack at this problem...
|
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...
|
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...
|
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...
| |
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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |