简体   繁体   中英

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

  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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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