[Tutor] TypeError: list objects are unhashable

Kent Johnson kent37 at tds.net
Sun Mar 15 15:00:48 CET 2009


On Sun, Mar 15, 2009 at 8:27 AM, qsqgeekyogdty at tiscali.co.uk
<qsqgeekyogdty at tiscali.co.uk> wrote:
>>>> l1 = [{'url': 'ws.geonames.org', 'type': 'findNearby',
> 'parameters': [50.100000000000001, 10.02]}, {'url': 'ws.geonames.org',
> 'type': 'findNearby', 'parameters': [50.100000000000001, 10.02]},
> {'url': 'ws.geonames.org', 'type': 'countryInfo', 'parameters':
> [50.100000000000001, 10.02]}, {'url': 'ws.geonames.org', 'type':
> 'countryInfo', 'parameters': [50.100000000000001, 10.02]}]
>
>>>> [dict(n) for n in set(tuple(n.items()) for n in l1)]
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> TypeError: list objects are unhashable
>
> How do I make this return two records instead of four?

If performance is not an issue you could use brute force:
In [9]: l2 = []

In [10]: for d in l1:
   ....:     if d not in l2:
   ....:         l2.append(d)

In [11]: l2
Out[11]:
[{'parameters': [50.100000000000001, 10.02],
  'type': 'findNearby',
  'url': 'ws.geonames.org'},
 {'parameters': [50.100000000000001, 10.02],
  'type': 'countryInfo',
  'url': 'ws.geonames.org'}]

if you have many dicts in l1 this is likely to be slow.

Where do the dicts come from? If they are from a database you could
ask the database for unique records.

Kent

Kent


More information about the Tutor mailing list