Home > Back-end >  Python dictionary to multiple list [closed]
Python dictionary to multiple list [closed]

Time:09-21

The current problem consists of the conversion of a dictionary to a list. I am unable to split the specific value of key and value pair into my desired results.

I have a dictionary that looks like this:

dict = [ {name:aa,age:12, id:121}, {name:bb,age:13, id:122},{name:cc,age:11, id:121}, {name:dd,age:15, id:122} ]

It has certain pairs of key and values and the 'ID' key is the most important of them.the ID value is repeated and so I am looking for lists of that value such that it would looks like this:

121 = [
{name:aa,age:12},
{name:cc,age:11}
]

122 = [
{name:bb,age:13},
{name:dd,age:15}
]

CodePudding user response:

I think this should work fine, just looping through the list of sub-dictionaries.

start_dict = [{'name':'aa','age':12,'id':121}, {'name':'bb','age':13,'id':122},{'name':'cc','age':11,'id':121}, {'name':'dd','age':15,'id':122}]

converted_dict = {}
for subdict in start_dict:
    if subdict['id'] not in converted_dict:
        converted_dict[subdict['id']] = [{k:v for k,v in subdict.items() if k != 'id'}]
    else:
        converted_dict[subdict['id']].append({k:v for k,v in subdict.items() if k != 'id'})
        
print(converted_dict)

{121: [{'name': 'aa', 'age': 12}, {'name': 'cc', 'age': 11}], 
 122: [{'name': 'bb', 'age': 13}, {'name': 'dd', 'age': 15}]}

CodePudding user response:

from collections import defaultdict

start_dict = [
    {'name': 'aa', 'age': 12, 'id': 121},
    {'name': 'bb', 'age': 13, 'id': 122},
    {'name': 'cc', 'age': 11, 'id': 121},
    {'name': 'dd', 'age': 15, 'id': 122},
]
new_dict = defaultdict(list)

for entry in start_dict:
    new_dict[entry["id"]].append(dict(name=entry["name"], age=entry["age"]))

print(dict(new_dict))

CodePudding user response:

You can use setdefault and with this set default list for value each key and append items to list of each key.

start_dict = [{'name':'aa','age':12,'id':121}, {'name':'bb','age':13,'id':122},{'name':'cc','age':11,'id':121}, {'name':'dd','age':15,'id':122}]

out = {}
for sd in start_dict:
    out.setdefault(sd['id'], [])
    out[sd['id']].append({'name': sd['name'], 'age': sd['age']})
print(out)

Output:

{
 121: [ 
       {'name': 'aa', 'age': 12}, 
       {'name': 'cc', 'age': 11}
      ], 
 122: [
       {'name': 'bb', 'age': 13}, 
       {'name': 'dd', 'age': 15}
      ]
}
  • Related