0

I am trying to find all the keys that include the corresponding values using the following code, I have the current output and expected output,can someone provide guidance on what I am doing wrong?

CODE:-

info = [

{'x':['y','z']},
{'a':['y','x']},
{'p':['q','z']},
{'z':['x','q']}

]

output_list = []
for d in info:
    for key,value in d.items():
        print (key,value)
        new_list,new_dict = [],{}
        for element in value:
            print (element)
            new_list.append(key)
            new_dict[key] = new_dict
            output_list.append(new_list)
print (output_list)

CURRENT OUTPUT:-

[['x', 'x'], ['x', 'x'], ['a', 'a'], ['a', 'a'], ['p', 'p'], ['p', 'p'], ['z', 'z'], ['z', 'z']]

EXPECTED OUTPUT:

[
{'y':['x','a']},
{'z' = ['x','p']},
{'x' = ['a','z']},
{'q' = ['p','z']}
]
wisecrack
  • 315
  • 2
  • 12

1 Answers1

1

Try this:

inverse_dict = {}
for d in info:
    for k, v in d.items():
        for a in v:
            inverse_dict.setdefault(a, []).append(k)
inverse_dict = [{k: v} for k, v in inverse_dict.items()]
[{'y': ['x', 'a']}, {'z': ['x', 'p']}, {'x': ['a', 'z']}, {'q': ['p', 'z']}]

You can create a dictionary whose keys are all the set of all the values of dictionaries in info and then make a list of dictionaries (one for each key) out of them.

PieCot
  • 3,564
  • 1
  • 12
  • 20
  • I wanted to post my answer but the question has been closed. You can do this in a single list comprehension like this `d = {}; [d.setdefault(x,[]).append(k) for dct in info for k,v in dct.items() for x in v]`. Then assign `output_list = [d]` – Joe Ferndz Feb 13 '21 at 09:08
  • It would be wrong, because `ouput_list` would not be a `list` of `dict`s (as required, one `dict` for each key), but a `list` with only one `dict`. – PieCot Feb 13 '21 at 09:22
  • Nope. Try it. by putting all the code inside [ ], it creates the dictionary inside. The list comprehension is not getting assigned to anything. It just creates the dictionary d. Then you can assign it to a list `output_list` – Joe Ferndz Feb 13 '21 at 09:31
  • I've tried, `output_list` contains only one `dict`, and it is wrong. Look carefully at the expected output. – PieCot Feb 13 '21 at 09:49