Dictionary from list?

Ivan A. Vigasin vig at ParallelGraphics.COM
Fri Oct 19 08:56:34 EDT 2001


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! It comes from functional programming?

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


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

Regards, Ivan <vig at parallelgraphics.com>
ICQ: 22181170





More information about the Python-list mailing list