[Tutor] Unique elements mapping
Sean Perry
shaleh at speakeasy.net
Fri Mar 25 19:42:06 CET 2005
Srinivas Iyyer wrote:
> Hi all:
>
> I have a question and I request groups help please.
>
> My list has two columns:
>
> Name State
> Drew Virginia
> Noel Maryland
> Niki Virginia
> Adams Maryland
> Jose Florida
> Monica Virginia
> Andrews Maryland
>
>
> I would like to have my ouput like this:
>
> Virginia : Drew,Niki,Monica
> Maryland: Noel,Adams, Andrews
> Florida: Jose
>
>
> Can you help how should I code :
>
>
> for line in my_list:
> key = line.split('\t')[0]
> val = line.split('\t')[1]
>
>
> dict = dict(zip(key,val))
>
> this was my strategy ... but I could not make it
> work..
You have the right idea. Just bad implementation (-:
uniques = {} # never name them 'dict', that is a type name in python
for line in my_list:
key, val = line.split('\t')
uniques.setdefault(val, []).append(key)
# in Python 2.4 the following two lines can be shortened to
# sorted_keys = sorted(unique.keys())
sorted_keys = unique.keys()
sorted_keys.sort()
for item in sort_keys:
print "%s: %s" % (item, ",".join(unique[item]))
So what we are doing is making a dict for which each element is a list
of names. The setdefault trick above is a neater way of saying:
if not uniques.has_key(val):
uniques[val] = []
uniques[val].append(key)
More information about the Tutor
mailing list