小编sar*_*912的帖子

从元素对列表创建字典

我想使用这个对列表创建一个字典:

pairs = [('a', 'c'), ('b', 'c'), ('b', 'e'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('c', 'e'), ('d', 'c'), ('e', 'c'), ('e', 'f')]
Run Code Online (Sandbox Code Playgroud)

我想返回这样的东西:

{ "a" : ["c"],
  "b" : ["c", "e"],
  "c" : ["a", "b", "d", "e"],
  "d" : ["c"],
  "e" : ["c", "f"],
  "f" : []}
Run Code Online (Sandbox Code Playgroud)

因此,基本上,该对中的每个元素都必须表示为键,即使它们有一个空列表。我尝试使用下面的代码:

graph = {}
for k, v in pairs:
  if k not in d:
    d[k] = []
  d[k].append(v) 
Run Code Online (Sandbox Code Playgroud)

但它仅返回该对中的第一个元素作为键:

{'a': ['c'],
 'b': ['c', 'e'],
 'c': ['a', 'b', 'd', 'e'],
 'd': ['c'],
 'e': …
Run Code Online (Sandbox Code Playgroud)

python dictionary list

1
推荐指数
1
解决办法
586
查看次数

标签 统计

dictionary ×1

list ×1

python ×1