Dictionary from list?
Michael Hudson
mwh at python.net
Fri Oct 19 09:18:10 EDT 2001
"Ivan A. Vigasin" <vig at ParallelGraphics.COM> writes:
> On Fri, 19 Oct 2001, Michael Hudson wrote:
>
> > />> def beargh(d):
> > |.. unique = []
> > |.. def ouch(x,y):
> > |.. if x is unique:
> > |.. return y
> > |.. else:
> > |.. d[x] = y
> > |.. return unique
> > |.. return ouch
> > \__
> > ->> d = {}
> > ->> reduce(beargh(d), ['a', 1, 'b', 2])
> > []
> > ->> d
> > {'a': 1, 'b': 2}
> Idea is great!
You mean that for real? I think it's foul. It abuses the
implementation details of reduce to do something that function was
never intended to do.
> It comes from functional programming?
No. There are side-effects all over the place!
> Your code doesn't work in my Python 2.1 ...
>
> t1.py:1: SyntaxWarning: local name 'd' in 'beargh' shadows use of 'd' as global in nested scope 'ouch'
> def beargh(d):
> t1.py:1: SyntaxWarning: local name 'unique' in 'beargh' shadows use of 'unique' as global in nested scope 'ouch'
> def beargh(d):
> Traceback (most recent call last):
> File "t1.py", line 12, in ?
> reduce(beargh(d), ['a', 1, 'b', 2])
> File "t1.py", line 4, in ouch
> if x is unique:
> NameError: global name 'unique' is not defined
You needed a "from __future__ import nested_scopes" in there
somewhere.
> I slighly modified your code and got the following:
>
> class beargh:
> def __init__(self,d):
> self.d = d
> def __call__(self,x,y):
> if x == []:
> return y
> else:
> self.d[x] = y
> return []
>
> d = {}
> reduce( beargh(d), ['a', 1, 'b', 2] )
> print d
Actually, that works almost as well as my code -- you get problems
with input like ['a', 1, [], 2], but you have problems with that
anyway as lists aren't hashable.
Just in case anyone hasn't got the message yet:
THE CODE I POSTED WAS DISGUSTING. DON'T EMULATE IT.
THE CODE I POSTED WAS DISGUSTING. DON'T EMULATE IT.
THE CODE I POSTED WAS DISGUSTING. DON'T EMULATE IT.
THE CODE I POSTED WAS DISGUSTING. DON'T EMULATE IT.
THE CODE I POSTED WAS DISGUSTING. DON'T EMULATE IT.
THE CODE I POSTED WAS DISGUSTING. DON'T EMULATE IT.
THE CODE I POSTED WAS DISGUSTING. DON'T EMULATE IT.
THE CODE I POSTED WAS DISGUSTING. DON'T EMULATE IT.
THE CODE I POSTED WAS DISGUSTING. DON'T EMULATE IT.
THE CODE I POSTED WAS DISGUSTING. DON'T EMULATE IT.
THE CODE I POSTED WAS DISGUSTING. DON'T EMULATE IT.
THE CODE I POSTED WAS DISGUSTING. DON'T EMULATE IT.
THE CODE I POSTED WAS DISGUSTING. DON'T EMULATE IT.
THE CODE I POSTED WAS DISGUSTING. DON'T EMULATE IT.
THE CODE I POSTED WAS DISGUSTING. DON'T EMULATE IT.
THE CODE I POSTED WAS DISGUSTING. DON'T EMULATE IT.
Cheers,
M.
--
Now this is what I don't get. Nobody said absolutely anything
bad about anything. Yet it is always possible to just pull
random flames out of ones ass.
-- http://www.advogato.org/person/vicious/diary.html?start=60
More information about the Python-list
mailing list