1

I have a dictionary:

dict = {'A':[1,2,5],'B':[3,6,13],'C':[2,3,6],'D':[4,6,8]}

I want to extract all the common elements into a new dictionary as keys with their corresponding values as the keys in dict which they are extracted from. What I want is:

newdict = {1:['A'],2:['A','C'],3:['B','C'],4:['D'],5:['A'],6:['B','C','D'],8:['D'],13:['B']} .

I have tried to compare values of each element by copying the dictionary dict and comparing each of the elements (dict1 is copy of dict):

for i, j in zip(range(len(dict)), range(len(dict1))):
    for m, n in zip(range(len(dict[i])), range(len(dict1[j]))):
        if dict[i][m] == dict1[j][n]:
            print(dict[i][m])
            
for i in range(len(dict)):
    for k in range(len(dict[i])):
        #print(dict[i][k])
        for j in range(dict[i+1][k], len(g)):
            #print(j)
            if dict[i][k] == dict[i+1][j]:
                print(dict[i][k]) 

However, I ended up with index out of range error or unable to get the proper keys even before being able to extract the common repeating values. Does anybody know how to do this?

1 Answers1

1

Simple solution using defaultdict (to reduce bloat code)

from collections import defaultdict

d2 = defaultdict(list)

for k,v in d.items():
  for number in v:
    d2[number].append(k)

>>> print(d2)
defaultdict(list,
            {1: ['A'],
             2: ['A', 'C'],
             3: ['B', 'C'],
             4: ['D'],
             5: ['A'],
             6: ['B', 'C', 'D'],
             8: ['D'],
             13: ['B']})

You can also use a normal dictionary, there's just some more checks to add:

d2 = {}

for k,v in d.items():
  for number in v:
    if number in d2:
      d2[number].append(k)
    else:
      d2[number] = [k]

Finally, avoid naming your dictionary dict, since it overwrites the built-in dict name.

rafaelc
  • 57,686
  • 15
  • 58
  • 82
  • Thanks for answering. But in case the the value for a key repeats as ['A','A'], how to remove the repititions of 'A' ? – Priyankush Ghosh Jun 06 '22 at 22:01
  • You can use a `set` intead of a `list` in the default dict. And have `d2[number] = {k}` and `d2[number].add(k)` in the second method. – rafaelc Jun 06 '22 at 22:02
  • The second method converts all the values to dictionaries instead of lists. Any way to get back lists format? – Priyankush Ghosh Jun 06 '22 at 22:09
  • @PriyankushGhosh they are not dictionaries. They are sets. You can always do, as a final step, `d2 = {k:list(v) for k,v in d2.items()}` to make the sets be lists again. – rafaelc Jun 06 '22 at 22:10