简体   繁体   English

从元素对列表创建字典

[英]create a dictionary from a list of pairs of elements

I want to create a dictionary using this list of pairs:我想使用这个对列表创建一个字典:

pairs = [('a', 'c'), ('b', 'c'), ('b', 'e'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('c', 'e'), ('d', 'c'), ('e', 'c'), ('e', 'f')]

I want to return something like this:我想返回这样的东西:

{ "a" : ["c"],
  "b" : ["c", "e"],
  "c" : ["a", "b", "d", "e"],
  "d" : ["c"],
  "e" : ["c", "f"],
  "f" : []}

So, basically, every element in the pair has to be represented as a key even if they have an empty list.因此,基本上,对中的每个元素都必须表示为一个键,即使它们有一个空列表。 I have tried using this code below:我试过使用下面的代码:

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

but it returns only the first element in the pair as key:但它只返回对中的第一个元素作为键:

{'a': ['c'],
 'b': ['c', 'e'],
 'c': ['a', 'b', 'd', 'e'],
 'd': ['c'],
 'e': ['c', 'f']} 
pairs = [('a', 'c'), ('b', 'c'), ('b', 'e'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('c', 'e'), ('d', 'c'), ('e', 'c'), ('e', 'f')]

d = {}
for k, v in pairs:
    d.setdefault(v, [])
    d.setdefault(k, []).append(v)

from pprint import pprint
pprint(d)

Prints:印刷:

{'a': ['c'],
 'b': ['c', 'e'],
 'c': ['a', 'b', 'd', 'e'],
 'd': ['c'],
 'e': ['c', 'f'],
 'f': []}

Adaptations needed to your existing code, which is:现有代码所需的调整,即:

graph = {}
for k, v in pairs:
  if k not in d:
    d[k] = []
  d[k].append(v) 
  1. You are calling the output dictionary graph when you initialise it but then d inside the loop.您在初始化时调用 output 字典graph ,然后在循环内调用d Probably you corrected this already (as otherwise you would be getting an error), but it should obviously be the same (say d ) in both cases.可能你已经纠正了这个(否则你会得到一个错误),但在两种情况下它显然应该是相同的(比如d )。

  2. If you want all the values to exist as keys in the dictionary (with empty lists if they do not exist as keys in the input dictionary), then simply add inside the loop the same thing as you are already doing with k , but with v instead:如果您希望所有值都作为字典中的键存在(如果它们在输入字典中不作为键存在,则使用空列表),那么只需在循环中添加与您已经使用k相同的东西,但使用v反而:

  if v not in d:
    d[v] = []

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM