dictionary_name = [{'id':'123','id_2':'5676'},{'id': '123','id_2':'4545'},{'id':'123','id_2':'8375'},{'id':'156','id_2':'9374'}]
I need to get:
result = { 'id': {'123': [5676, 4545, 8375]}, {'156': [9374]} }
So far, I have tried the following
result = {}
for d in dictionary_name:
identifier = d['id']
if identifier not in dictionary_name:
result[identifier] = d['id_2']
print(result)
But it only outputs:
{ '123': '8375', '156': '9374' }
CodePudding user response:
Try this
result = {}
for i in range(len(dictionary_name)):
identifier = dictionary_name[i]['id']
if identifier not in result:
result[identifier] = [dictionary_name[i]['id_2']]
else:
result[identifier].append(dictionary_name[i]['id_2'])
print(result)
The output would be:
{'123': ['5676', '4545', '8375'], '156': ['9374']}