invert dictionary with list &c
anton muhin
antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru
Fri Nov 28 07:13:53 EST 2003
Des Small wrote:
> anton muhin <antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru> writes:
>
>
>>Des Small wrote:
>>
>>>Des Small <des.small at bristol.ac.uk> writes:
>>>
>>>
>>>>anton muhin <antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru> writes:
>>>
>>>[...]
>>
>>Or like this:
>>
>>def dict_update(iter, func, default, d):
>> def process_element(d, e):
>> d[e[0]] = func(d.get(e[0], default), *e[1:])
>> return d
>>
>> return reduce(process_element, iter, d)
>>
>>def count(l):
>> return dict_update(l, lambda x: x + 1, 0, {})
>
>
> With these I get:
>
>
>>>>count(["yes", "yes", "no"])
>
>
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> File "<stdin>", line 2, in count
> File "<stdin>", line 5, in dict_update
> File "<stdin>", line 3, in process_element
> TypeError: <lambda>() takes exactly 1 argument (3 given)
>
> I tried to write something that would work on more generic arguments,
> but I couldn't do it without explicit type checking, so I gave up.
>
> [...]
>
> Des
> has now embalmed versions in his utils collection.
>
My fault :( A small patch:
def count(l):
return dict_update([(e,) for e in l], lambda x: x + 1, 0, {})
now
print count(['yes', 'yes', 'no'])
print count('aabbbc')
prints
{'yes': 2, 'no': 1}
{'a': 2, 'c': 1, 'b': 3}
regards,
anton.
More information about the Python-list
mailing list