0

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))

2 Answers 2

5

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))
Sign up to request clarification or add additional context in comments.

Comments

0

You can also use setdefault when using normal dict's

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.