[Tutor] Re: Unique Items in Lists
Kent Johnson
kent37 at tds.net
Thu Jan 27 11:57:20 CET 2005
Brian van den Broek wrote:
> Wolfram Kraus said unto the world upon 2005-01-27 03:24:
>
>> Brian van den Broek wrote:
>>> for key in items_dict.copy(): # Try it without the .copy()
>>> if items_dict[key] == 1: # and see what happens.
>>> del items_dict[key]
>>>
>>> dict_keys = items_dict.keys()
>>> dict_keys.sort()
>>
>>
>>> for key in dict_keys:
>>> print '%s occurred %s times' %(key, items_dict[key])
>>
>>
>> This whole part can be rewritten (without sorting, but in Py2.4 you
>> can use sorted() for this) with a list comprehension (Old Python2.1
>> style, with a newer version the keys() aren't needed):
>> for k,v in [(k, items_dict[k]) \
>> for k in items_dict.keys() if items_dict[k] > 1]:
>> print '%s occurred %s times' %(key, items_dict[key])
I think it is clearer to filter the list as it is printed. And dict.iteritems() is handy here, too.
for k, v in items_dict.iteritems():
if v > 1:
print '%s occurred %s times' % (k, v)
Kent
More information about the Tutor
mailing list