The Goal
I'm attempting to combine duplicate dictionaries in a nested dict together for a large amount of dict (~ 10,000).
For my specific case, I'm mainly looking to have all the related information (e.g. Batch & Items) of an identifier (e.g. USERID) be in one dictionary, which is in a list containing similar dictionaries. As an example with a smaller size:
Input
raw = [
{'USERID': 'USERID1', 'BATCH': 'NUM1304', 'ITEMS': '105'},
{'USERID': 'USERID15', 'BATCH': 'NUM1323', 'ITEMS': '122'},
{'USERID': 'USERID1', 'BATCH': 'NUM1365', 'ITEMS': '98'},
{'USERID': 'USERID12', 'BATCH': 'NUM1365', 'ITEMS': '76'},
{'USERID': 'USERID1', 'BATCH': 'NUM1376', 'ITEMS': '55'},
{'USERID': 'USERID3', 'BATCH': 'NUM1396', 'ITEMS': '151'},
{'USERID': 'USERID7', 'BATCH': 'NUM1398', 'ITEMS': '69'},
{'USERID': 'USERID7', 'BATCH': 'NUM1398', 'ITEMS': '126'},
{'USERID': 'USERID12', 'BATCH': 'NUM1422', 'ITEMS': '76'},
{'USERID': 'USERID15', 'BATCH': 'NUM1455', 'ITEMS': '77'},
{'USERID': 'USERID1', 'BATCH': 'NUM1465', 'ITEMS': '97'}
]
Output
raw = [
{'USERID': 'USERID1', 'BATCH': ['NUM1304', 'NUM1365', 'NUM1376', 'NUM1465'], 'ITEMS': ['105', '98', '55', '97']},
{'USERID': 'USERID15', 'BATCH': ['NUM1323', 'NUM1455'], 'ITEMS': ['122', '77']},
{'USERID': 'USERID12', 'BATCH': ['NUM1365', 'NUM1422'], 'ITEMS': ['76', '76']},
{'USERID': 'USERID3', 'BATCH': ['NUM1396'], 'ITEMS': ['151']},
{'USERID': 'USERID7', 'BATCH': ['NUM1398'], 'ITEMS': ['69']}
]
What's Done
I have already completed the following:
# Converts the batch & items values to lists to allow for extending #
def Corrector(raw):
i = 0
while i != len(raw):
raw[i]['BATCH'] = [raw[i]['BATCH']]
raw[i]['ITEMS'] = [raw[i]['ITEMS']]
i += 1
# Goes through two dictionaries and combines their values together #
def DuplicateCombiner(o_dict1, o_dict2):
for key, value in o_dict2.items():
if key in o_dict1 and isinstance(value, list):
o_dict1[key].extend(value)
else:
o_dict1[key] = value
# Removes duplicates from the original nest #
def DuplicateRemover(raw):
i = 0
raw_copy = []
users = []
while i != len(raw):
if raw[i]['USERID'] not in users:
users.append(raw[i]['USERID'])
raw_copy.append(raw[i])
i += 1
return raw_copy
My Attempt
I have used the following, which is very ineffective as it loops millions of times with a larger size, but did function for the example I gave earlier. However, I am looking for something that will function with a larger size, preferably without maxing out my RAM :).
def Combiner(self):
for i in raw:
for n in raw:
if i['USER ID'] != n['USER ID']: # If they're not the same USERID
continue
if i['BATCH'][0] == n['BATCH'][0]: # If they're the same dict
continue
DuplicateCombiner(i, n)
Also, I am using python 3.8.12. Any assistance is greatly appreciated.