Sunday, March 7, 2010

comp.lang.python - 25 new messages in 9 topics - digest

comp.lang.python
http://groups.google.com/group/comp.lang.python?hl=en

comp.lang.python@googlegroups.com

Today's topics:

* Asynchronous HTTP client - 4 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/8d12ca848ffb171e?hl=en
* best practices: is collections.defaultdict my friend or not? - 1 messages, 1
author
http://groups.google.com/group/comp.lang.python/t/4bfdc60d3f58c960?hl=en
* Problem with regular expression - 5 messages, 5 authors
http://groups.google.com/group/comp.lang.python/t/d54dd678daaf5f9d?hl=en
* Conditional based on whether or not a module is being used - 1 messages, 1
author
http://groups.google.com/group/comp.lang.python/t/ee22c223fa73a429?hl=en
* time_struct - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/1905a949453756ba?hl=en
* compiler with python - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/cb204e8c749a46be?hl=en
* a simple def how-to - 7 messages, 4 authors
http://groups.google.com/group/comp.lang.python/t/63641d2590adb295?hl=en
* Duplicate keys in dict? - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/4372a73f1e51af35?hl=en
* (www.globlepurchase.com)Paypal payment Discount Wholesale/Retail(UGGBOOTS,
SHOES,CLOTHES,HANDBAG,WATCH,JEANS,JERSEY,T- - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/b369aaf6be1c2ad7?hl=en

==============================================================================
TOPIC: Asynchronous HTTP client
http://groups.google.com/group/comp.lang.python/t/8d12ca848ffb171e?hl=en
==============================================================================

== 1 of 4 ==
Date: Sat, Mar 6 2010 10:53 pm
From: Ping


Hi,

I'm trying to find a way to create an asynchronous HTTP client so I
can get responses from web servers in a way like

async_http_open('http://example.com/', callback_func)
# immediately continues, and callback_func is called with response
as arg when it is ready

It seems twisted can do it, but I hesitate to bring in such a big
package as a dependency because my client should be light. Asyncore
and asynchat are lighter but they don't speak HTTP. The asynchttp
project on sourceforge is a fusion between asynchat and httplib, but
it hasn't been updated since 2001 and is seriously out of sync with
httplib.

I'd appreciate it if anyone can shed some lights on this.

Thanks,
Ping


== 2 of 4 ==
Date: Sun, Mar 7 2010 5:12 am
From: Lie Ryan


On 03/07/2010 05:53 PM, Ping wrote:
> Hi,
>
> I'm trying to find a way to create an asynchronous HTTP client so I
> can get responses from web servers in a way like
>
> async_http_open('http://example.com/', callback_func)
> # immediately continues, and callback_func is called with response
> as arg when it is ready
>
> It seems twisted can do it, but I hesitate to bring in such a big
> package as a dependency because my client should be light. Asyncore
> and asynchat are lighter but they don't speak HTTP. The asynchttp
> project on sourceforge is a fusion between asynchat and httplib, but
> it hasn't been updated since 2001 and is seriously out of sync with
> httplib.
>
> I'd appreciate it if anyone can shed some lights on this.

If you want something quite lightweight, you can spawn a thread for the
call:

import threading, urllib
class AsyncOpen(threading.Thread):
def __init__(self, url, callback):
super(AsyncOpen, self).__init__()
self.url = url
self.callback = callback
def run(self):
# of course change urllib to httplib-something-something
content = urllib.urlopen(self.url).read()
self.callback(content)

def asyncopen(url, callback):
AsyncOpen(url, callback).start()

def cb(content):
print content

asyncopen('http://www.google.com', cb)


== 3 of 4 ==
Date: Sun, Mar 7 2010 5:16 am
From: exarkun@twistedmatrix.com


On 06:53 am, ping.nsr.yeh@gmail.com wrote:
>Hi,
>
>I'm trying to find a way to create an asynchronous HTTP client so I
>can get responses from web servers in a way like
>
> async_http_open('http://example.com/', callback_func)
> # immediately continues, and callback_func is called with response
>as arg when it is ready
>
>It seems twisted can do it, but I hesitate to bring in such a big
>package as a dependency because my client should be light. Asyncore
>and asynchat are lighter but they don't speak HTTP. The asynchttp
>project on sourceforge is a fusion between asynchat and httplib, but
>it hasn't been updated since 2001 and is seriously out of sync with
>httplib.

Why should it be "light"? In what way would using Twisted cause
problems for you?

Jean-Paul


== 4 of 4 ==
Date: Sun, Mar 7 2010 6:57 am
From: exarkun@twistedmatrix.com


On 02:40 pm, ping.nsr.yeh@gmail.com wrote:
>2010/3/7 <exarkun@twistedmatrix.com>
>>On 06:53 am, ping.nsr.yeh@gmail.com wrote:
>>>Hi,
>>>
>>>I'm trying to find a way to create an asynchronous HTTP client so I
>>>can get responses from web servers in a way like
>>>
>>> async_http_open('http://example.com/', callback_func)
>>> # immediately continues, and callback_func is called with response
>>>as arg when it is ready
>>>
>>>It seems twisted can do it, but I hesitate to bring in such a big
>>>package as a dependency because my client should be light. Asyncore
>>>and asynchat are lighter but they don't speak HTTP. The asynchttp
>>>project on sourceforge is a fusion between asynchat and httplib, but
>>>it hasn't been updated since 2001 and is seriously out of sync with
>>>httplib.
>>
>>Why should it be "light"? In what way would using Twisted cause
>>problems
>>for you?
>>
>>Jean-Paul
>
>I'm writing an open source python client for a web service. The client
>may
>be used in all kinds of environments - Linux, Mac OS X, Windows, web
>hosting, etc by others. It is not impossible to have twisted as a
>dependency, but that makes deployment a larger job than simply
>uploading a
>Python file.

Twisted is packaged for many Linux distributions (perhaps most of them).
Many web hosts provide it. It's also shipped with OS X.

Windows may be an issue, but note that there's a binary Windows
installer (as of 10.0, an MSI, so installation can be easily automated).
>I'm willing to use twisted, but I'd like to explore lighter
>alternatives
>first.

Jean-Paul

==============================================================================
TOPIC: best practices: is collections.defaultdict my friend or not?
http://groups.google.com/group/comp.lang.python/t/4bfdc60d3f58c960?hl=en
==============================================================================

== 1 of 1 ==
Date: Sun, Mar 7 2010 1:33 am
From: Mark Lawrence


Pete Emerson wrote:
> On Mar 5, 6:10 pm, Andreas Waldenburger <use...@geekmail.INVALID>
> wrote:
>> On Fri, 5 Mar 2010 17:22:14 -0800 (PST) Pete Emerson
>>
>>
>>
>>
>>
>> <pemer...@gmail.com> wrote:
>>> [snip]
>>>>>> data['one'] = {}
>>>>>> data['one']['two'] = 'three'
>>>>>> print data
>>> {'one': {'two': 'three'}}
>>> And through some research, I discovered collections.defaultdict (new
>>> in Python 2.5, FWIW):
>>>>>> import collections
>>>>>> data = collections.defaultdict(dict)
>>>>>> data['one']['two'] = 'three'
>>>>>> print data
>>> defaultdict(<type 'dict'>, {'one': {'two': 'three'}})
>>> [snip]
>>> Your thoughts and comments are very much appreciated. I think my brain
>>> already knows some of the answers, but my heart ... well, perl and I
>>> go way back. Loving python so far, though.
>> Oh, by the way: That defaultdict route is a pretty solid solution. Not
>> sure what problem you're trying to solve -- depending on your usecase,
>> there might be a better approach.
>>
>> If you're just asking hypothetically and you're trying to apply a
>> Perl idiom to Python, there probably *is* a better solution.
>>
>> /W
>>
>> --
>> INVALID? DE!
>
> I found out about the need to declare the higher level as I was
> reading in a JSON struct into a dict and then adding a new entry at a
> lower level. Mostly just proof of concept stuff as I'm learning
> python. I'm not sure that the use of defaultdict is really warranted
> for me anywhere just yet. Mostly, I don't want to convert my perl to
> python, that seems very counterproductive. Thank you very much for
> your insight.
>
> I was a little frightened of doing "import this" ("Hey, kid, run rm -
> rf / and see what happens!"), but did, and the words are wise. :)
>
> Pete

After reading the words of wisdom try "import this" a second time and
watch what happens, it's quite interesting if you're not expecting the
output.

Mark Lawrence.


==============================================================================
TOPIC: Problem with regular expression
http://groups.google.com/group/comp.lang.python/t/d54dd678daaf5f9d?hl=en
==============================================================================

== 1 of 5 ==
Date: Sun, Mar 7 2010 2:32 am
From: Joan Miller


I would to convert the first string to upper case. But this regular
expression is not matching the first string between quotes.

re.sub("'(?P<id>\w+)': [^{]", "\g<id>FOO", str)

# string to non-matching
'foo': {

# strings to matching
'bar': 'bar2'
'bar': None
'bar': 0
'bar': True

So, i.e., from the first string I would to get:
'BAR': 'bar2'


Any help? please
Thanks in advance


== 2 of 5 ==
Date: Sun, Mar 7 2010 4:52 am
From: News123


Hi Joan,

Joan Miller wrote:
> I would to convert the first string to upper case. But this regular
> expression is not matching the first string between quotes.
>
> re.sub("'(?P<id>\w+)': [^{]", "\g<id>FOO", str)
>
> # string to non-matching
> 'foo': {
>
> # strings to matching
> 'bar': 'bar2'
> 'bar': None
> 'bar': 0
> 'bar': True
>
> So, i.e., from the first string I would to get:
> 'BAR': 'bar2'
>
I'm a little slow today and don't exactly understand your question.

Could you perhaps add some examples of input lines and what you would
like to extract?

example:
input = "first word to Upper"
output = "FIRST word to Upper"


bye


N

>
> Any help? please
> Thanks in advance


== 3 of 5 ==
Date: Sun, Mar 7 2010 5:03 am
From: Steve Holden


Joan Miller wrote:
> I would to convert the first string to upper case. But this regular
> expression is not matching the first string between quotes.
>
> re.sub("'(?P<id>\w+)': [^{]", "\g<id>FOO", str)
>
> # string to non-matching
> 'foo': {
>
> # strings to matching
> 'bar': 'bar2'
> 'bar': None
> 'bar': 0
> 'bar': True
>
> So, i.e., from the first string I would to get:
> 'BAR': 'bar2'
>
>
> Any help? please
> Thanks in advance

Well your pattern is identifying the right bits, but re.sub() replaces
everything it matches:

>>> import re
>>> strings = """\
... 'bar': 'bar2'
... 'bar': None
... 'bar': 0
... 'bar': True""".split("\n")
>>> for s in strings:
... print re.sub("'(?P<id>\w+)': [^{]", "\g<id>FOO", s)
...
barFOObar2'
barFOOone
barFOO
barFOOrue
>>>

What you need to fix is the replacement. Take a look at the
documentation for re.sub: you will need to provide a function to apply
the upper-case transformation, and the example there should show you how.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/

== 4 of 5 ==
Date: Sun, Mar 7 2010 5:35 am
From: Tim Chase


Joan Miller wrote:
> I would to convert the first string to upper case. But this regular
> expression is not matching the first string between quotes.
>
> re.sub("'(?P<id>\w+)': [^{]", "\g<id>FOO", str)

Well, my first thought is that you're not using raw strings, so
you're not using the regexps and replacements you think you are.

r"'(?P<id>\w+)': [^{]"

will match the lines of interest. The replacement will eat the
opening & closing single-quote, colon, and first character.

> # string to non-matching
> 'foo': {
>
> # strings to matching
> 'bar': 'bar2'
> 'bar': None
> 'bar': 0
> 'bar': True
>
> So, i.e., from the first string I would to get:
> 'BAR': 'bar2'

I think you'd have to use a function/lambda to do the
case-conversion:

re.sub(
r"'(?P<id>\w+)(?=': [^{])",
lambda m: "'" + m.group('id').upper(),
string_of_interest
)

Or you could just forgo regexps and use regular string functions
like split(), startswith(), and upper()

-tkc


== 5 of 5 ==
Date: Sun, Mar 7 2010 6:10 am
From: Paul McGuire


On Mar 7, 4:32 am, Joan Miller <pelok...@gmail.com> wrote:
> I would to convert the first string to upper case. But this regular
> expression is not matching the first string between quotes.
>
Is using pyparsing overkill? Probably. But your time is valuable,
and pyparsing let's you knock this out in less time than it probably
took to write your original post.


Use pyparsing's pre-defined expression sglQuotedString to match your
entry key in quotes:

key = sglQuotedString

Add a parse action to convert to uppercase:

key.setParseAction(lambda tokens:tokens[0].upper())

Now define the rest of your entry value (be sure to add the negative
lookahead so we *don't* match your foo entry):

entry = key + ":" + ~Literal("{")

If I put your original test cases into a single string named 'data', I
can now use transformString to convert all of your keys that don't
point to '{'ed values:

print entry.transformString(data)

Giving me:

# string to non-matching
'foo': {

# strings to matching
'BAR': 'bar2'
'BAR': None
'BAR': 0
'BAR': True

Here's the whole script:

from pyparsing import sglQuotedString, Literal

key = sglQuotedString
key.setParseAction(lambda tokens:tokens[0].upper())
entry = key + ":" + ~Literal("{")

print entry.transformString(data)

And I'll bet that if you come back to this code in 3 months, you'll
still be able to figure out what it does!

-- Paul

==============================================================================
TOPIC: Conditional based on whether or not a module is being used
http://groups.google.com/group/comp.lang.python/t/ee22c223fa73a429?hl=en
==============================================================================

== 1 of 1 ==
Date: Sun, Mar 7 2010 4:34 am
From: Steve Holden


Vinay Sajip wrote:
[...]
> Well, the logging package is available in Python and ready for use and
> pretty much battle tested, so why not use that? Are you planning to
> use third-party libraries in your Python work, or write everything
> yourself? If you are planning to use third party libraries, how would
> their logging be hooked into your logger module? And if not, is it
> good to have two logging systems in parallel?
>
> Of course as the maintainer of Python's logging package, you'd expect
> me to be biased in favour of it. You maybe shouldn't let that sway
> you ;-)
>
Vinay:

My own impression of the logging module, formed from trying to use its
documentation in the past, is that it's somewhat unapproachable, and
difficult to use for simple purposes.

I am happy to say that now I see the current (3.1) documentation it has
improved to the point where I would be happy to try using it again.
Thanks for your long-term maintenance of this package.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/


==============================================================================
TOPIC: time_struct
http://groups.google.com/group/comp.lang.python/t/1905a949453756ba?hl=en
==============================================================================

== 1 of 1 ==
Date: Sun, Mar 7 2010 5:50 am
From: moerchendiser2k3


Hi,

can anyone tell me how to return a time_struct from the timemodule in
my own C-Module?
Is that possible? I can just find one function in timefuncs.h, but it
doesnt return any PyObject.

Thanks in advance.

moerchendiser2k3

==============================================================================
TOPIC: compiler with python
http://groups.google.com/group/comp.lang.python/t/cb204e8c749a46be?hl=en
==============================================================================

== 1 of 2 ==
Date: Sun, Mar 7 2010 6:57 am
From: Stefan Behnel


mohamed issolah, 06.03.2010 14:07:
> I want to create a compiler which transform a code like pascal code (that
> what I do in C) to "quad"
> In C, I use BISON and FLEX tools.

Hi,

please stop starting new threads for the same topic. Instead, reply to
responses you get.

Stefan

== 2 of 2 ==
Date: Sun, Mar 7 2010 7:16 am
From: Mark Lawrence


Alf and Steven Howe, please don't top post, it makes it all but
impossible to follow a thread. Darn!:)

Mark Lawrence.

Alf P. Steinbach wrote:
> Since Mohamed is talking about compilation I think it's more likely he's
> talking about an intermediate program represention based on quad tuples
> like
>
> (OP, DESTINATION, ARG1, ARG2)
>
> Cheers,
>
> - Alf
>
>
> * Steven Howe:
>> Is it possible he's talking about a 'quad core'? as in a CPU? In that
>> case I think he wants
>> to optimize a python program for a multiprocessor core with four
>> processors.
>>
>> sph
>>
>>
>> On 03/06/2010 07:56 AM, Dave Angel wrote:
>>> mohamed issolah wrote:
>>>>
>>>> 2010/3/6 Dave Angel <davea@ieee.org>
>>>>
>>>>> mohamed issolah wrote:
>>>>>
>>>>>> hey,
>>>>>>
>>>>>> How can I construct a compiler with python just for informatiom .,
>>>>>> I have
>>>>>> habit to construct it with C language,
>>>>>>
>>>>>> sorry for my english ;-)
>>>>>>
>>>>>>
>>>>> You need to tell us what you're really trying to do, what tools you're
>>>>> willing to use, and probably why you want it. And if you're not
>>>>> sure about
>>>>> your English, keep the sentence structure straightforward.
>>>>>
>>>>> Let me make a couple of wild guesses:
>>>>>
>>>>
>>>>
>>>>> You want to design and build a compiler that takes xml information
>>>>> as its
>>>>> source code, and compiles those xml files into Intel x86 machine
>>>>> code. The
>>>>> compiler and the resulting executable needs to run on an x86 Linux
>>>>> machine.
>>>>> Your previous experience was in doing this sort of thing in C, but
>>>>> you want
>>>>> to try it with Python instead. You want to do it without using the
>>>>> lxml
>>>>> libraries.
>>>>>
>>>>> You want to build a python compiler, that takes python source code and
>>>>> produces Java byte code files. You'd like to do this in C, but
>>>>> don't want
>>>>> to use any of the available existing CPython or Jython source
>>>>> code. Your
>>>>> goal is not to make a commercially viable product, but to learn as
>>>>> much as
>>>>> possible in the process.
>>>>>
>>>>>
>>>>> DaveA
>>>>>
>>>>
>>>> hey,
>>>>
>>>> I want to create a compiler which transform a code like pascal code
>>>> (that
>>>> what I do in C) to "quad"
>>>> In C, I use BISON and FLEX tools.
>>>>
>>>>
>>> I've forwarded your message to the list, and fixed your top-posting
>>> by moving your response to the bottom. I don't have a clue what
>>> "quad" is, unless it's a synonym for Forth.
>>>
>>> You haven't specified the OS you'll be using to run the compiler, nor
>>> the one you're targeting, so some of these choices may not be
>>> useful. For example, the first one is Linux only.
>>>
>>> http://www.freenet.org.nz/python/pybison/
>>> PyBison - Python binding for Bison/Flex
>>>
>>> http://freshmeat.net/projects/yeanpypa/
>>> http://www.slash-me.net/dev/snippets/yeanpypa/documentation.html
>>>
>>> http://www.python.org/community/sigs/retired/parser-sig/towards-standard/
>>>
>>>
>>> Or you could go here, which has links to (most of) these and others.
>>> http://wiki.python.org/moin/LanguageParsing
>>>
>>> DaveA


==============================================================================
TOPIC: a simple def how-to
http://groups.google.com/group/comp.lang.python/t/63641d2590adb295?hl=en
==============================================================================

== 1 of 7 ==
Date: Sun, Mar 7 2010 7:05 am
From: vsoler


Hello,

My script starts like this:

book=readFromExcelRange('book')
house=readFromExcelRange('house')
table=readFromExcelRange('table')
read=readFromExcelRange('read')
...

But I would like to have something equivalent, like...

ranges=['book','house','table','read']
for i in ranges:
var[i]=readFromExcelRange(i)

which does not work. I assume I should be using globals() instead of
var, but I do not know how to write my script.

Can anybody help?


== 2 of 7 ==
Date: Sun, Mar 7 2010 7:23 am
From: Andreas Waldenburger


On Sun, 7 Mar 2010 07:05:26 -0800 (PST) vsoler
<vicente.soler@gmail.com> wrote:

> Hello,
>
> My script starts like this:
>
> book=readFromExcelRange('book')
> house=readFromExcelRange('house')
> table=readFromExcelRange('table')
> read=readFromExcelRange('read')
> ...
>
> But I would like to have something equivalent, like...
>
> ranges=['book','house','table','read']
> for i in ranges:
> var[i]=readFromExcelRange(i)
>
> which does not work. I assume I should be using globals() instead of
> var, but I do not know how to write my script.
>
> Can anybody help?

One additional line, and it works (all the following code is untested,
I might have goofed it up somewhere, but you get the idea):

ranges=['book','house','table','read']
var = {}
for i in ranges:
var[i]=readFromExcelRange(i)

Or, more succinctly:

var = dict((i, readFromExcelRange(i)) for i in ranges)

although that looks a bit crowded. Perhaps

rd = readFromExcelRange
var = dict((i, rd(i)) for i in ranges)

looks better, but not by much, IMO.

In Python 3 you can also just say

var = {i:readFromExcelRange(i) for i in ranges}

(I think. I don't have Python 3.) This looks comparatively neat,
because there are no nesting parens.


And just in case you think it's a good idea to meddle with globals and
create actual "variables": it's not. You absolutely want dictionaries
here. It's basically a bad idea to create names *implicitly* that
you're going to use *explicitly*. (That is, it is in Python anyway,
because it does not provide a clean and clear way of doing this. Other
languages might provide that sort of thing, and it might be awesome,
but in Python, no sir.)

/W

--
INVALID? DE!

== 3 of 7 ==
Date: Sun, Mar 7 2010 7:23 am
From: John Posner


On 3/7/2010 10:05 AM, vsoler wrote:
> Hello,
>
> My script starts like this:
>
> book=readFromExcelRange('book')
> house=readFromExcelRange('house')
> table=readFromExcelRange('table')
> read=readFromExcelRange('read')
> ...
>
> But I would like to have something equivalent, like...
>
> ranges=['book','house','table','read']
> for i in ranges:
> var[i]=readFromExcelRange(i)
>
> which does not work. I assume I should be using globals() instead of
> var, but I do not know how to write my script.
>
> Can anybody help?

var = [] # create empty list
for i in ranges:
var.append(readFromExcelRange(i))

-or-

var = [ readFromExcelRange(i) for i in ranges ]

-or-

var = map(readFromExcelRange, ranges)

-John


== 4 of 7 ==
Date: Sun, Mar 7 2010 7:57 am
From: vsoler


On 7 mar, 16:23, Andreas Waldenburger <use...@geekmail.INVALID> wrote:
> On Sun, 7 Mar 2010 07:05:26 -0800 (PST) vsoler
>
>
>
> <vicente.so...@gmail.com> wrote:
> > Hello,
>
> > My script starts like this:
>
> > book=readFromExcelRange('book')
> > house=readFromExcelRange('house')
> > table=readFromExcelRange('table')
> > read=readFromExcelRange('read')
> > ...
>
> > But I would like to have something equivalent, like...
>
> > ranges=['book','house','table','read']
> > for i in ranges:
> >     var[i]=readFromExcelRange(i)
>
> > which does not work. I assume I should be using globals() instead of
> > var, but I do not know how to write my script.
>
> > Can anybody help?
>
> One additional line, and it works (all the following code is untested,
> I might have goofed it up somewhere, but you get the idea):
>
> ranges=['book','house','table','read']
> var = {}
> for i in ranges:
>     var[i]=readFromExcelRange(i)
>
> Or, more succinctly:
>
> var = dict((i, readFromExcelRange(i)) for i in ranges)
>
> although that looks a bit crowded. Perhaps
>
> rd = readFromExcelRange
> var = dict((i, rd(i)) for i in ranges)
>
> looks better, but not by much, IMO.
>
> In Python 3 you can also just say
>
> var = {i:readFromExcelRange(i) for i in ranges}
>
> (I think. I don't have Python 3.) This looks comparatively neat,
> because there are no nesting parens.
>
> And just in case you think it's a good idea to meddle with globals and
> create actual "variables": it's not. You absolutely want dictionaries
> here. It's basically a bad idea to create names *implicitly* that
> you're going to use *explicitly*. (That is, it is in Python anyway,
> because it does not provide a clean and clear way of doing this. Other
> languages might provide that sort of thing, and it might be awesome,
> but in Python, no sir.)
>
> /W
>
> --
> INVALID? DE!

Thank you Andreas.

Your comprehensive answer makes a lot of sense to me.


== 5 of 7 ==
Date: Sun, Mar 7 2010 7:59 am
From: vsoler


On 7 mar, 16:23, John Posner <jjpos...@optimum.net> wrote:
> On 3/7/2010 10:05 AM, vsoler wrote:
>
>
>
> > Hello,
>
> > My script starts like this:
>
> > book=readFromExcelRange('book')
> > house=readFromExcelRange('house')
> > table=readFromExcelRange('table')
> > read=readFromExcelRange('read')
> > ...
>
> > But I would like to have something equivalent, like...
>
> > ranges=['book','house','table','read']
> > for i in ranges:
> >      var[i]=readFromExcelRange(i)
>
> > which does not work. I assume I should be using globals() instead of
> > var, but I do not know how to write my script.
>
> > Can anybody help?
>
> var = []    # create empty list
> for i in ranges:
>      var.append(readFromExcelRange(i))
>
>   -or-
>
> var = [ readFromExcelRange(i) for i in ranges ]
>
>   -or-
>
> var = map(readFromExcelRange, ranges)
>
> -John

John,

Thank you for your help. Perhaps the solution you are suggesting is
not exactly what I was looking for, but helped anyway.


== 6 of 7 ==
Date: Sun, Mar 7 2010 8:16 am
From: John Posner


On 3/7/2010 10:59 AM, vsoler wrote:
>
> Thank you for your help. Perhaps the solution you are suggesting is
> not exactly what I was looking for, but helped anyway.

Oops, I was thinking list, not dict. Too fast, and not enough coffee!

-John


== 7 of 7 ==
Date: Sun, Mar 7 2010 8:42 am
From: Steven D'Aprano


On Sun, 07 Mar 2010 07:05:26 -0800, vsoler wrote:

> Hello,
>
> My script starts like this:
>
> book=readFromExcelRange('book')
> house=readFromExcelRange('house')
> table=readFromExcelRange('table')
> read=readFromExcelRange('read')
> ...
>
> But I would like to have something equivalent, like...
>
> ranges=['book','house','table','read']
> for i in ranges:
> var[i]=readFromExcelRange(i)
>
> which does not work. I assume I should be using globals() instead of
> var, but I do not know how to write my script.
>
> Can anybody help?

Yes. Use a dict instead.

ranges=['book','house','table','read']
data = {}
for name in ranges:
data[name] = readFromExcelRange(name)

# and later...

item = 'table'
print "The range '%s' is %s" % (item, data[item])

--
Steven

==============================================================================
TOPIC: Duplicate keys in dict?
http://groups.google.com/group/comp.lang.python/t/4372a73f1e51af35?hl=en
==============================================================================

== 1 of 3 ==
Date: Sun, Mar 7 2010 8:23 am
From: vsoler


Hello,

My code snippet reads data from excel ranges. First row and first
column are column headers and row headers respectively. After reding
the range I build a dict.

................'A'..............'B'
'ab'............3................5
'cd'............7................2
'cd'............9................1
'ac'............7................2

d={('ab','A'): 3, ('ab','B'): 5, ('cd','A'): 7, ...

However, as you can see there are two rows that start with 'cd', and
dicts, AFAIK do not accept duplicates.

What is the best workaround for this? Should I discard dicts? Should I
somehow have under 'cd'... a list of values?

One of the difficulties I find here is that I want to be able to
easily sum all the values for each row key: 'ab', 'cd' and 'ac'.
However, using lists inside dicts makes it a difficult issue for me.

What is the best approach for this problem? Can anybody help?


== 2 of 3 ==
Date: Sun, Mar 7 2010 8:46 am
From: News123


vsoler wrote:
> Hello,
>
> My code snippet reads data from excel ranges. First row and first
> column are column headers and row headers respectively. After reding
> the range I build a dict.
>
> ................'A'..............'B'
> 'ab'............3................5
> 'cd'............7................2
> 'cd'............9................1
> 'ac'............7................2
>
> d={('ab','A'): 3, ('ab','B'): 5, ('cd','A'): 7, ...
>
> However, as you can see there are two rows that start with 'cd', and
> dicts, AFAIK do not accept duplicates.

Normall dicts are used if you want to access your data at a later point
in time by the key name.

Do you want to be able to do this?


Then what would you expect to receive for d[('cd','A')] ?

The first value? the second value? both values?

Could you perhaps change further occurences of 'cd' with 'cd1' , 'cd2' ,
'cd3', ... ?

Not knowing your exact context makes it difficult to suggest solutions?

perhaps you could switch to a list containing a tuple of (rowname,rowdict)


l = [ ('ab', { 'A': 3 , 'B': 5 } ),
'cd', { 'A': 7 , 'B': 2 } ),
'cd', { 'A': 9 , 'B': 1 } ),
'ac', { ... }
]


bye

N

>
> What is the best workaround for this? Should I discard dicts? Should I
> somehow have under 'cd'... a list of values?
>
> One of the difficulties I find here is that I want to be able to
> easily sum all the values for each row key: 'ab', 'cd' and 'ac'.
> However, using lists inside dicts makes it a difficult issue for me.
>
> What is the best approach for this problem? Can anybody help?


== 3 of 3 ==
Date: Sun, Mar 7 2010 8:53 am
From: Steven D'Aprano


On Sun, 07 Mar 2010 08:23:13 -0800, vsoler wrote:

> Hello,
>
> My code snippet reads data from excel ranges. First row and first column
> are column headers and row headers respectively. After reding the range
> I build a dict.
>
> ................'A'..............'B'
> 'ab'............3................5
> 'cd'............7................2
> 'cd'............9................1
> 'ac'............7................2
>
> d={('ab','A'): 3, ('ab','B'): 5, ('cd','A'): 7, ...
>
> However, as you can see there are two rows that start with 'cd', and
> dicts, AFAIK do not accept duplicates.

> One of the difficulties I find here is that I want to be able to easily
> sum all the values for each row key: 'ab', 'cd' and 'ac'. However,
> using lists inside dicts makes it a difficult issue for me.

Given the sample above, what answer do you expect for summing the 'cd'
row? There are four reasonable answers:

7 + 2 = 9
9 + 1 = 10
7 + 2 + 9 + 1 = 19
Error

You need to decide what you want to do before asking how to do it.

--
Steven

==============================================================================
TOPIC: (www.globlepurchase.com)Paypal payment Discount Wholesale/Retail(
UGGBOOTS,SHOES,CLOTHES,HANDBAG,WATCH,JEANS,JERSEY,T-
http://groups.google.com/group/comp.lang.python/t/b369aaf6be1c2ad7?hl=en
==============================================================================

== 1 of 1 ==
Date: Sun, Mar 7 2010 8:27 am
From: daiwen15@yahoo.com


PAYPAL payment wholesale SHOES

(NIKE,ADIDAS,LV,GUCCI,CHANEL,PRADA,POLO,UGG BOOTS,D&G,DIOR AND SO ON)
PAYPAL payment wholesale CLOTHING and jeans(A&F,D&G,ED

HARDAY,BAPE,BBC,LV,GUCCI,ARMANI,POLO,POUL SMITH AND SO ON)
http://www.globlepurchase.com
PAYPAL payment WATCH(ROLEX,OMEGA,CHANEL,LV,CARTIER,IWC,GUCCI,RADO AND

SO ON)
PAYPAL payment HANDBAG

(LV,GUCCI,CHANEL,PRADA,POLO,COACH,FENDI,CHLOE,BUBERRY,JUICY AND SO ON)
paypal payment brand cap,shawl,belt,wallet,under wear,and so on.

More detail land, address:http://www.globlepurchase.com


==============================================================================

You received this message because you are subscribed to the Google Groups "comp.lang.python"
group.

To post to this group, visit http://groups.google.com/group/comp.lang.python?hl=en

To unsubscribe from this group, send email to comp.lang.python+unsubscribe@googlegroups.com

To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.python/subscribe?hl=en

To report abuse, send email explaining the problem to abuse@googlegroups.com

==============================================================================
Google Groups: http://groups.google.com/?hl=en

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate