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

Organized lists inside dictionary based off existing dictionary

I have an existing dictionary in Python that is formatted as follows, the length and values can change when the code is ran though.

{'1': 'Dog',
 '2': 'Dog',
 '3': 'Cat',
 '4': 'Dog',
 '5': 'Cat',
 '6': 'Cat',
 '7': 'Dog',
 '8': 'Dog',
 '9': 'Rabbit',
 '10': 'Dog',
 '11': 'Cat'}

I want to reformat it so it is as follows

{
 "Dog" : ['1', '2', '4', '7', '8', 10],
 "Cat" : ['3', '5', '6', '11'],
 "Rabbit" : ['9']
}

I am struggling to come up with a for loop that can loop through the existing dict and create the new one.

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

>Solution :

You can use collections.defaultdict or dict.setdefault and insert element in list.

from collections import defaultdict

dct = defaultdict(list)
dct_2 = {}

inp = {'1': 'Dog','2': 'Dog','3': 'Cat','4': 'Dog',
 '5': 'Cat','6': 'Cat','7': 'Dog','8': 'Dog',
 '9': 'Rabbit','10': 'Dog','11': 'Cat'}


for k,v in inp.items():
    dct[v].append(k)
    
    dct_2.setdefault(v, []).append(k)
    
print(dct)
print(dct_2)

Output:

# dct
defaultdict(<class 'list'>, {'Dog': ['1', '2', '4', '7', '8', '10'], 'Cat': ['3', '5', '6', '11'], 'Rabbit': ['9']})

# dct_2
{'Dog': ['1', '2', '4', '7', '8', '10'], 'Cat': ['3', '5', '6', '11'], 'Rabbit': ['9']}
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