1

I am trying to solve the following problem using dict and list comprehension. Given

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

expected output is ::

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

So far, I have only been able to come up with ::

output = {}
for (k,v) in input.items():
    for x in v:
        if x[0] not in output:
            output[x[0]] = [k]
        else:
            output[x[0]].append(k)

What would be a possible one line dict+list comprehension method to do this?

Arnav
  • 51
  • 5
  • 5
    My 2 cents: refrain from the urge of one liners just for the sake of it – Julien Sep 15 '20 at 06:05
  • 1
    ugly way: `{v: [k for k in d if v in d[k]] for v in set(itertools.chain.from_iterable(input.values()))}` – jizhihaoSAMA Sep 15 '20 at 06:07
  • The moderator mentions that this question is a duplicate of https://stackoverflow.com/questions/35491223/inverting-a-dictionary-with-list-values. However, the other question does not talk about dict+list comprehension – Arnav Sep 15 '20 at 06:16
  • You can use the following code, unfortunatly I can't post this as an answer because the question is closed. `output_dict = {x:[key for (key, val) in input_dict.items() if x in val] for (k, v) in input_dict.items() for x in v}` – Bhavye Mathur Sep 15 '20 at 06:39

0 Answers0