sarandonga2912
sarandonga2912

Reputation: 97

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']} 

Upvotes: 1

Views: 644

Answers (2)

alani
alani

Reputation: 13079

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] = []

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195438

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': []}

Upvotes: 6

Related Questions