My initial problem was to initialize a bunch of dictionaries at the start of a
function.
I did not want to do
def fn():
a = {}
b = {}
c = {}
. . .
z = {}
simply because it was ugly and wasted screen space.
First I tried:
for x in (a,b,c,d,e,f,g): x = {}
which didn't work (but frankly I didn't really expect it to.)
Then I tried:
for x in ('a','b','c','d','e','f','g'): locals()[x]={}
which did what I wanted, in the interpreter. When I put it inside a function,
it doesn't seem to work. If I print locals() from inside the function, I can
see them, and they appear to be fine, but the first time I try to access one
of them I get a "NameError: global name 'a' is not defined"
Now obviously I could easily avoid this problem by just initializing each
dictionary, but is there something wrong about my understanding of locals,
that my function isn't behaving the way I expect? -----Original Message----- From: py*******************************************@pyth on.org [mailto:py***************************************** **@python.org]On Behalf Of Dennis Lee Bieber Sent: Tuesday, November 09, 2004 10:31 AM To: py*********@python.org Subject: Re: Determining combination of bits
On Mon, 8 Nov 2004 21:18:36 -0800, "news.west.cox.net" <se*********@cox.net> declaimed the following in comp.lang.python:
Note: 2^1 = 2, so your dictionary is already in error...
The dictionary was filled with arbitrary values, not { x : 2^x } values like you might have thought.
Well, you had stated "powers of two"... If all you wanted is a bit mapping you could probably drop the dictionary and just use a list of the values, indexed by the bit position, and my first attempt logic...
It is actually more like {1:123, 2:664, 4:323, 8:990, 16:221... etc}
CheckBoxes = [ "FirstChoice", "SecondChoice", "ThirdChoice", "FourthChoice", "FifthChoice", "SixthChoice" ]
for num in [22, 25, 9]: bit = 0 while num: if num & 1: print CheckBoxes[bit], bit = bit + 1 num = num >> 1 print
SecondChoice ThirdChoice FifthChoice FirstChoice FourthChoice FifthChoice FirstChoice FourthChoice
where "num" is the sum of the checkbox index values (or whatever selection mechanism is used), assuming /they/ were set up in 2^(n+1) scheme (n = bit position, starting with 0)...
-- > ================================================== ============ < > wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wu******@dm.net | Bestiaria Support Staff < > ================================================== ============ < > Home Page: <http://www.dm.net/~wulfraed/> < > Overflow Page: <http://wlfraed.home.netcom.com/> < -- http://mail.python.org/mailman/listinfo/python-list
================================================== ============================
This message is for the sole use of the intended recipient. If you received
this message in error please delete it and notify us. If this message was
misdirected, CSFB does not waive any confidentiality or privilege. CSFB
retains and monitors electronic communications sent through its network.
Instructions transmitted over this system are not binding on CSFB until they
are confirmed by us. Message transmission is not guaranteed to be secure.
================================================== ============================ 8 2581
It is almost certain that you should use either a list of dictionaries
or a dictionary containing other dictionaries for this. Creation of
26 distinct dictionaries is almost never a good solution as it makes
it nearly impossible to iterate over them and would make code to
manipulate them unable to be generalized easily.
Example:
#
# To create a list of dictionaries
#
list_of_dicts=[]
for i in range(26):
list_of_dicts.append({})
#
# Now you can reference each dictionary as:
#
# list_of_dicts[0], list_of_dicts[1], ...
#
or
import string
dict_of_dicts={}
for letter in string.ascii_lowercase:
dict_of_dicts[letter]={}
#
# Now you can reference each dictionary as:
#
# dict_of_dicts['a'], dict_of_dicts['b'], ...
Larry Bates
Frohnhofer, James wrote: My initial problem was to initialize a bunch of dictionaries at the start of a function.
I did not want to do def fn(): a = {} b = {} c = {} . . . z = {} simply because it was ugly and wasted screen space.
First I tried:
for x in (a,b,c,d,e,f,g): x = {}
which didn't work (but frankly I didn't really expect it to.) Then I tried:
for x in ('a','b','c','d','e','f','g'): locals()[x]={}
which did what I wanted, in the interpreter. When I put it inside a function, it doesn't seem to work. If I print locals() from inside the function, I can see them, and they appear to be fine, but the first time I try to access one of them I get a "NameError: global name 'a' is not defined"
Now obviously I could easily avoid this problem by just initializing each dictionary, but is there something wrong about my understanding of locals, that my function isn't behaving the way I expect?
-----Original Message----- From: py*******************************************@pyth on.org [mailto:py***************************************** **@python.org]On Behalf Of Dennis Lee Bieber Sent: Tuesday, November 09, 2004 10:31 AM To: py*********@python.org Subject: Re: Determining combination of bits
On Mon, 8 Nov 2004 21:18:36 -0800, "news.west.cox.net" <se*********@cox.net> declaimed the following in comp.lang.python:
Note: 2^1 = 2, so your dictionary is already in error...
The dictionary was filled with arbitrary values, not { x : 2^x } values like you might have thought.
Well, you had stated "powers of two"... If all you wanted is a bit mapping you could probably drop the dictionary and just use a list of the values, indexed by the bit position, and my first attempt logic...
It is actually more like {1:123, 2:664, 4:323, 8:990, 16:221... etc}
CheckBoxes = [ "FirstChoice", "SecondChoice", "ThirdChoice", "FourthChoice", "FifthChoice", "SixthChoice" ]
for num in [22, 25, 9]: bit = 0 while num: if num & 1: print CheckBoxes[bit], bit = bit + 1 num = num >> 1 print
SecondChoice ThirdChoice FifthChoice FirstChoice FourthChoice FifthChoice FirstChoice FourthChoice
where "num" is the sum of the checkbox index values (or whatever selection mechanism is used), assuming /they/ were set up in 2^(n+1) scheme (n = bit position, starting with 0)...
-- > ================================================== ============ < > wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wu******@dm.net | Bestiaria Support Staff < > ================================================== ============ < > Home Page: <http://www.dm.net/~wulfraed/> < > Overflow Page: <http://wlfraed.home.netcom.com/> < -- http://mail.python.org/mailman/listinfo/python-list
================================================== ============================ This message is for the sole use of the intended recipient. If you received this message in error please delete it and notify us. If this message was misdirected, CSFB does not waive any confidentiality or privilege. CSFB retains and monitors electronic communications sent through its network. Instructions transmitted over this system are not binding on CSFB until they are confirmed by us. Message transmission is not guaranteed to be secure. ================================================== ============================
[Frohnhofer, James] My initial problem was to initialize a bunch of dictionaries at the start of a function.
I did not want to do def fn(): a = {} b = {} c = {} . . . z = {} simply because it was ugly and wasted screen space.
Use exec(). for c in 'abcdefghijklmnopqrstuvwxyz':
exec c + ' = {}'
Of course, as others have pointed out, the whole idea is likely misguided and
you would be better served with a list of unnamed dictionaries.
Raymond Hettinger
Frohnhofer, James wrote: My initial problem was to initialize a bunch of dictionaries at the start of a function.
I did not want to do def fn(): a = {} b = {} c = {} . . . z = {} simply because it was ugly and wasted screen space.
Here is a bunch of dictionaries that spring into existence by what is
believed to be magic :-) class AllDicts:
.... def __getattr__(self, name):
.... d = {}
.... setattr(self, name, d)
.... return d
.... def __repr__(self):
.... items = self.__dict__.items()
.... items.sort()
.... return "\n".join(map("%s -> %r".__mod__, items))
.... ad = AllDicts() ad.a[1] = 99 ad.b[2] = 42 ad.b[3] = 11 ad
a -> {1: 99}
b -> {2: 42, 3: 11}
Peter
On Tue, 9 Nov 2004 16:40:48 -0000, "Frohnhofer, James" <ja**************@csfb.com> wrote: My initial problem was to initialize a bunch of dictionaries at the start of a function.
I did not want to do def fn(): a = {} b = {} c = {} . . . z = {} simply because it was ugly and wasted screen space.
First I tried:
for x in (a,b,c,d,e,f,g): x = {}
which didn't work (but frankly I didn't really expect it to.) Then I tried:
for x in ('a','b','c','d','e','f','g'): locals()[x]={}
which did what I wanted, in the interpreter. When I put it inside a function, it doesn't seem to work. If I print locals() from inside the function, I can see them, and they appear to be fine, but the first time I try to access one of them I get a "NameError: global name 'a' is not defined"
Now obviously I could easily avoid this problem by just initializing each dictionary, but is there something wrong about my understanding of locals, that my function isn't behaving the way I expect?
Others explained why locals()[x] worked interactively, and not in a function,
but if you just want a one-liner, you could just unpack a listcomp: a,b,c = [{} for i in xrange(3)] a,b,c
({}, {}, {})
If you have single-letter names, you can avoid the count by stepping through the letters:
x,y,z = [{} for dont_care in 'xyz'] x,y,z
({}, {}, {})
Or if you have a long target list and you can just type it and copy/paste it like:
fee,fie,fo,fum,bim,bah = [{} for ignore in 'fee,fie,fo,fum,bim,bah'.split(',')] fee,fie,fo,fum,bim,bah
({}, {}, {}, {}, {}, {}) map(id, (fee,fie,fo,fum,bim,bah))
[9440400, 9440976, 9438816, 9441120, 9440256, 9440544]
The dicts are separate, as you can see:
id(a),id(b),id(c)
(9153392, 9153248, 9439248) a,b,c = [{i:chr(i+ord('0'))} for i in xrange(3)] a,b,c
({0: '0'}, {1: '1'}, {2: '2'})
Regards,
Bengt Richter
Larry Bates a écrit : It is almost certain that you should use either a list of dictionaries or a dictionary containing other dictionaries for this. Creation of 26 distinct dictionaries is almost never a good solution as it makes it nearly impossible to iterate over them and would make code to manipulate them unable to be generalized easily.
Example:
# # To create a list of dictionaries # list_of_dicts=[] for i in range(26): list_of_dicts.append({})
or just
list_of_dicts = [{} for i in range(26)]
or if you want a dict of dicts :
dod = dict([(i, {}) for i in range(26)])
Peter, respect :)
For interest sake, how would such a thing look with new-style classes? My
(likely misinformed) impression is that __getattr__ for example, doesn't
behave in quite the same way?
thx
Caleb
On Tue, 09 Nov 2004 20:12:15 +0100, Peter Otten <__*******@web.de> wrote: Here is a bunch of dictionaries that spring into existence by what is believed to be magic :-)
class AllDicts: ... def __getattr__(self, name): ... d = {} ... setattr(self, name, d) ... return d .. def __repr__(self): ... items = self.__dict__.items() ... items.sort() ... return "\n".join(map("%s -> %r".__mod__, items)) ... ad = AllDicts() ad.a[1] = 99 ad.b[2] = 42 ad.b[3] = 11 ad
a -> {1: 99} b -> {2: 42, 3: 11}
Peter
Caleb Hattingh <caleb1 <at> telkomsa.net> writes: For interest sake, how would such a thing look with new-style classes? My (likely misinformed) impression is that __getattr__ for example, doesn't behave in quite the same way?
Just the same[1] =) class AllDicts(object):
.... def __getattr__(self, name):
.... d = {}
.... setattr(self, name, d)
.... return d
.... def __repr__(self):
.... items = self.__dict__.items()
.... items.sort()
.... return '\n'.join(['%s -> %r' % item for item in items])
.... ad = AllDicts() ad.a[1] = 99 ad.b[2] = 42 ad.b[3] = 11 ad
a -> {1: 99}
b -> {2: 42, 3: 11}
I believe that __getattr__ works just the same (but to check for yourself, see http://docs.python.org/ref/attribute-access.html). I think what you're thinking
of is __getattribute__ which new-style classes offer *in addition* to
__getattr__. While __getattr__ is called only if an attribute is not found,
__getattribute__ is called unconditionally for every attribute access.
Steve
[1] modulo my preference for list comprehensions/generator expressions instead
of map
Steve,
Not only did you answer my silly question, but also the question I
actually wanted to ask ...__getattribute__ is what I was thinking of.
thats cool :)
thx
Caleb
On Thu, 11 Nov 2004 20:30:18 +0000 (UTC), Steven Bethard
<st************@gmail.com> wrote: Caleb Hattingh <caleb1 <at> telkomsa.net> writes: For interest sake, how would such a thing look with new-style classes? My (likely misinformed) impression is that __getattr__ for example, doesn't behave in quite the same way?
Just the same[1] =)
class AllDicts(object): ... def __getattr__(self, name): ... d = {} ... setattr(self, name, d) ... return d ... def __repr__(self): ... items = self.__dict__.items() ... items.sort() ... return '\n'.join(['%s -> %r' % item for item in items]) ... ad = AllDicts() ad.a[1] = 99 ad.b[2] = 42 ad.b[3] = 11 ad a -> {1: 99} b -> {2: 42, 3: 11}
I believe that __getattr__ works just the same (but to check for yourself, see http://docs.python.org/ref/attribute-access.html). I think what you're thinking of is __getattribute__ which new-style classes offer *in addition* to __getattr__. While __getattr__ is called only if an attribute is not found, __getattribute__ is called unconditionally for every attribute access.
Steve
[1] modulo my preference for list comprehensions/generator expressions instead of map This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Michael Ellis |
last post by:
Hi,
I have some data files with lines in space-delimited <name> <value>
format. There are multiple name-value pairs per line.
Is there a cleaner idiom than the following for reading each line...
|
by: Fábio Mendes |
last post by:
I'm sorry if it's an replicate. Either my e-mail program is messing with
things or the python-list sent my msg to /dev/null. I couldn't find
anything related in previous PEP's, so here it goes a...
|
by: Andrew |
last post by:
Newb here... For one of my programs I want to initialize a variable for
each letter of the alphabet. For example, a,b,c = 0,0,0. I don't think
this works, but I'm wondering if I can do something...
|
by: Siemel Naran |
last post by:
What is a good idiom for handling a lazy object? I see 2 good
possibilities. Any more, any comments? Which way do people here use?
(1)
class Thing {
public:
Thing(double x, double y) :...
|
by: Christoph Zwerschke |
last post by:
This is probably a FAQ, but I dare to ask it nevertheless since I
haven't found a satisfying answer yet: Why isn't there an "ordered
dictionary" class at least in the standard list? Time and again...
|
by: Per |
last post by:
http://jaynes.colorado.edu/PythonIdioms.html
"""Use dictionaries for searching, not lists. To find items in common
between two lists, make the first into a dictionary and then look for
items in...
|
by: Mark |
last post by:
Hi, I'm new to python and looking for a better idiom to use for the
manner I have been organising my python scripts. I've googled all over
the place about this but found absolutely nothing.
I'm...
|
by: Noah Roberts |
last post by:
Some little tidbit I just ran into that might help some, especially
novice programmers.
If you are using the pimpl idiom, as you probably should be most of the
time, then it is very...
|
by: cnb |
last post by:
Are dictionaries the same as hashtables?
|
by: lllomh |
last post by:
Define the method first
this.state = {
buttonBackgroundColor: 'green',
isBlinking: false, // A new status is added to identify whether the button is blinking or not
}
autoStart=()=>{
|
by: Mushico |
last post by:
How to calculate date of retirement from date of birth
|
by: DJRhino |
last post by:
Was curious if anyone else was having this same issue or not....
I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM)
The start time is equivalent to 19:00 (7PM) in Central...
|
by: tracyyun |
last post by:
Hello everyone,
I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
|
by: giovanniandrean |
last post by:
The energy model is structured as follows and uses excel sheets to give input data:
1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
|
by: Teri B |
last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course.
0ne-to-many. One course many roles.
Then I created a report based on the Course form and...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM)
Please note that the UK and Europe revert to winter time on...
|
by: isladogs |
last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, Mike...
| |