Home > Software engineering >  Organized lists inside dictionary based off existing dictionary
Organized lists inside dictionary based off existing dictionary

Time:08-25

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.

CodePudding user response:

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']}
  • Related