Home > Mobile >  Python - split one list to smaller lists conditionally
Python - split one list to smaller lists conditionally

Time:02-02

Consider following list

all_values = [
    {"a": "first_type"},
    {"a": "second_type"}, {"a": "second_type"},
    {"a": "third_type"}
]

I would like to build a dict:

sorted_objs = {
   "first": [{"a": "first_type"}],
   "second": [{"a": "second_type"}, {"a": "second_type"}],
   "third": [{"a": "third_type"}]
}

What I do:

for obj in all_values:
    if obj["a"] == "first_type":
        sorted_objs["first"].append(obj)
    elif obj["a"] == "second_type":
        sorted_objs["second"].append(obj)
    elif obj["a"] == "third_type":
        sorted_objs["third"].append(obj)

I wonder how I can improve that? All_values list might be a little bit long so maybe I should think about performance too.

CodePudding user response:

You can use collections.defaultdict and append each dict in a list base key on split('_'):

from collections import defaultdict
res = defaultdict(list)

for dct in all_values:
    for k,v in dct.items():
        num = v.split('_')[0]
        res[num].append(dct)
print(res)

Output:

{
    'first': [{'a': 'first_type'}], 
    'second': [{'a': 'second_type'}, {'a': 'second_type'}], 
    'third': [{'a': 'third_type'}]
}

CodePudding user response:

There's not a lot of room for improvement, here's my suggestion:

-Add a list defining the desired order

all_values = [
    {"a": "first_type"},
    {"a": "second_type"}, {"a": "second_type"},
    {"a": "third_type"}
]

order = ["first_type","second_type","third_type"]

def orderSort(li):
    res = {}
    for name in order:
        res[name] = [e for e in li if (name==e["a"])]
    return res

print(orderSort(all_values))

Output:

{
   'first_type': [{'a': 'first_type'}],
   'second_type': [{'a': 'second_type'}, {'a': 'second_type'}],
   'third_type': [{'a': 'third_type'}]
}

CodePudding user response:

Below function can be used to extract keys and then update the list

all_values = [
{"a": "first_type"},
{"a": "second_type"}, {"a": "second_type"},
{"a": "third_type"}]

sorted_obj={}
for item in all_values:
    element=list( item.values())[0].split('_')[0]
    if  element in sorted_obj.keys():
        sorted_obj[element].append(item)
    else:
        sorted_obj[element]=[item]

output

{'first': [{'a': 'first_type'}],
 'second': [{'a': 'second_type'}, {'a': 'second_type'}],
 'third': [{'a': 'third_type'}]}
  • Related