Building unique comma-delimited list?

Roy Smith roy at panix.com
Wed Jan 5 17:05:40 EST 2005


I've got a silly little problem that I'm solving in C++, but I got to
thinking about how much easier it would be in Python.  Here's the
problem:

You've got a list of words (actually, they're found by searching a
data structure on the fly, but for now let's assume you've got them as
a list).  You need to create a comma-delimited list of these words.
There might be duplicates in the original list, which you want to
eliminate in the final list.  You don't care what order they're in,
except that there is a distinguised word which must come first if it
appears at all.

Some examples ("foo" is the distinguised word): 

["foo"] => "foo"
["foo", "bar"] => "foo, bar"
["bar", "foo"] => "foo, bar"
["bar", "foo", "foo", "baz", "bar"] => "foo, bar, baz" or "foo, baz, bar"

The best I've come up with is the following.  Can anybody think of a
simplier way?

--------------------
words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"]

# Eliminate the duplicates; probably use set() in Python 2.4
d = dict()
for w in words:
        d[w] = w

if d.has_key ("foo"):
        newWords = ["foo"]
        del (d["foo"])
else:
        newWords = []

for w in d.keys():
        newWords.append (w)

s = ', '.join (newWords)
print s
--------------------



More information about the Python-list mailing list