Is there a better, pythonic way to do this?
dictionary, python, set
Solution
the line of code:
adDict[adId] = set(userId)
is unlikely to do what you want -- it will treat string `userId` as a sequence of letters, so for example if `userId` was `aleax` you'd get a set with four items, just like, say, `set(['a', 'l', 'e', 'x'])`. Later, an `.add(userId)` when `userId` is `aleax` again will add a fifth item, the string `'aleax'`, because `.add` (differently from the set initializer, which takes an iterable as its argument) takes a single item as its argument.
To make a set with a single item, use `set([userId])` instead.
This is a reasonably frequent bug so I wanted to explain it clearly. That being said, `defaultdict` as suggested in other answers is clearly the right approach (avoid `setdefault`, that was never a good design and doesn't have good performance either, as well as being pretty murky).
I would also avoid the kinda-overkill of `csv` in favor of a simple loop with a .split and .strip on each line...
Problem
This is my first python program - Requirement: Read a file consisting of {adId UserId} in each line. For each adId, print the number of unique userIds. Here is my code, put together from reading the python docs. Could you give me feedback on how I can write this in more python-ish way? CODE : ``` import csv adDict = {} reader = csv.reader(open("some.csv"), delimiter=' ') for row in reader: adId = row[0] userId = row[1] if ( adId in adDict ): adDict[adId].add(userId) else: adDict[adId] = set(userId) for key, value in adDict.items(): print (key, ',' , len(value)) ``` Thanks.