-1

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    Can you post the code you have written so far? – C_Z_ Aug 24 '22 at 19:30
  • Does this answer your question? [How to reverse a dictionary that has repeated values](https://stackoverflow.com/questions/2823315/how-to-reverse-a-dictionary-that-has-repeated-values) – mkrieger1 Aug 24 '22 at 19:31

1 Answers1

1

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']}
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
  • 1
    As shown [here](https://stackoverflow.com/a/2823367) and [here](https://stackoverflow.com/a/60307026). – mkrieger1 Aug 24 '22 at 19:33
  • So it works when I declare the dictionary but when I generate the dictionary (via json response) I get the error RuntimeError: dictionary changed size during iteration – DrewTheTester Aug 24 '22 at 20:38