zzzbbx
zzzbbx

Reputation: 10141

Create list of tuples from empty dict

I would like to create a dict where the value is a list of tuples

The code below produces a dict with lists of numbers, not list of tuples

mydict = {}
for line in file:
  # read a
  # read b
  # read c 
  mydict[a] = (b, c) if a not in mydict else mydict[a].append((b, c))

Upvotes: 0

Views: 351

Answers (2)

Brendan Abel
Brendan Abel

Reputation: 37539

You can also use setdefault when using normal dict's

mydict = {}
mydict.setdefault(a, list()).append((b,c))

Upvotes: 0

Daniel
Daniel

Reputation: 42758

Use defaultdict:

from collections import defaultdict

mydict = defaultdict(list)
for line in file:
    a,b,c = line.split() # or something else
    mydict[a].append((b,c))

Upvotes: 5

Related Questions