For a unique key ID get all other keys' values python dictionary

Question:

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' }

Asked By: Jessica V

||

Answers:

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']}
Answered By: Mohammad Tehrani
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.