Harshal Parekh
Harshal Parekh

Reputation: 6027

Concisely fill dictionary

I have a file in this format:

1,abc
1,def
2,abc
3,abc
3,def

I am loading this file into a dictionary like this:

d = dict()
datareader = csv.reader(open(filename, "r"))

for row in datareader:
    if row[0] in d:
        d.get(row[0]).add(row[1])
    else:
        d[row[0]] = {row[1]}

It loads its successfully and the output is (which is what I want):

{'1': {'abc', 'def'}, '2': {'abc'}, '3': {'abc', 'def'}}

Is it possible to write the if/else condition in one line? If so, how?

Any other ideas on how can I make this code concise?

Upvotes: 1

Views: 53

Answers (1)

Marat
Marat

Reputation: 15738

built-in collections module has just the thing, defaultdict:

from collections import defaultdict

d = defaultdict(set)
datareader = csv.reader(open(filename, "r"))

for key, value in datareader:
    d[key].add(value)

Upvotes: 5

Related Questions