从空dict创建元组列表

Bob*_*Bob 0 python dictionary tuples

我想创建一个dict,其值是一个元组列表

下面的代码生成一个带有数字列表的字典,而不是元组列表

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))
Run Code Online (Sandbox Code Playgroud)

Dan*_*iel 5

用途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))
Run Code Online (Sandbox Code Playgroud)