Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract common elements of values (which are lists) of dictionary and map them back to their keys as their new values?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 knows how to do this?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading